Objects and Arrays

In JavaScript, objects and arrays are fundamental data structures used to store collections of data. Understanding how to use them effectively is key to writing clean and maintainable JavaScript code.

Objects

An object in JavaScript is a collection of key-value pairs, where keys are strings (or Symbols) and values can be of any data type. Objects are used to store and organize data and are extremely versatile in JavaScript.

Creating an Object

You can create an object using object literals or by using the Object constructor.

Example using object literals:

let person = {
  name: "Alice",
  age: 30,
  isStudent: false,
};

Example using the Object constructor:

let car = new Object();
car.brand = "Toyota";
car.model = "Corolla";
car.year = 2021;
Accessing Object Properties

You can access properties of an object using dot notation or bracket notation.

Example

let person = {
  name: "Alice",
  age: 30,
};

console.log(person.name); // Dot notation: Output -> "Alice"
console.log(person["age"]); // Bracket notation: Output -> 30
Adding and Modifying Properties

To add or modify a property, you can use either dot or bracket notation.

Example

let person = {
  name: "Alice",
};
person.age = 30; // Adding a new property
person.name = "Bob"; // Modifying an existing property

console.log(person); // Output -> { name: "Bob", age: 30 }
Removing Properties

You can remove a property from an object using the delete keyword.

Example

let person = {
  name: "Alice",
  age: 30,
};
delete person.age;

console.log(person); // Output -> { name: "Alice" }
Nested Objects

Objects can have other objects as values, allowing for nested structures.

Example

let student = {
  name: "John",
  grade: {
    math: 90,
    science: 85,
  },
};

console.log(student.grade.math); // Output -> 90

Arrays

An array is a special type of object that holds an ordered collection of values. Arrays are useful for storing lists of items.

Creating an Array

You can create an array using array literals or the Array constructor.

Example using array literals:

let fruits = ["apple", "banana", "cherry"];

Example using the Array constructor:

let numbers = new Array(1, 2, 3, 4);
Accessing Elements

Elements in an array are accessed using zero-based indexing.

Example

let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Output -> "apple"
console.log(fruits[2]); // Output -> "cherry"
Modifying Elements

You can modify elements in an array by assigning new values to specific indexes.

Example

let fruits = ["apple", "banana", "cherry"];
fruits[1] = "blueberry"; // Modify the element at index 1

console.log(fruits); // Output -> ["apple", "blueberry", "cherry"]
Adding Elements

To add elements to an array, you can use methods like push, unshift, or directly assign values to specific indexes.

  • push() adds elements to the end of an array.
  • unshift() adds elements to the beginning of an array.

Example

let fruits = ["apple", "banana"];
fruits.push("cherry"); // Adds "cherry" to the end
fruits.unshift("mango"); // Adds "mango" to the beginning

console.log(fruits); // Output -> ["mango", "apple", "banana", "cherry"]
Removing Elements

To remove elements from an array, you can use methods like pop, shift, or splice.

  • pop() removes the last element.
  • shift() removes the first element.
  • splice() removes elements from a specific position.

Example

let fruits = ["apple", "banana", "cherry"];
fruits.pop(); // Removes "cherry"
fruits.shift(); // Removes "apple"

console.log(fruits); // Output -> ["banana"]
Iterating Over Arrays

You can iterate over arrays using loops like for, for...of, or using array methods like forEach.

Example using for loop:

let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Example using forEach:

fruits.forEach((fruit) => console.log(fruit));

Array Methods

JavaScript provides many useful methods to manipulate arrays:

  • map(): Creates a new array by applying a function to each element.
  • filter(): Creates a new array with elements that meet a specific condition.
  • reduce(): Reduces an array to a single value by applying a function.
  • find(): Returns the first element that satisfies a condition.
  • includes(): Checks if an array contains a specific value.

Example using map and filter:

let numbers = [1, 2, 3, 4, 5];
let squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // Output -> [1, 4, 9, 16, 25]

let evenNumbers = numbers.filter((num) => num % 2 === 0);
console.log(evenNumbers); // Output -> [2, 4]

Objects vs. Arrays

  • Objects are used to store data that has key-value pairs, ideal for representing complex entities.
  • Arrays are used to store ordered lists of data, suitable for sequential items.

Example to illustrate both:

let student = {
  name: "Alice",
  subjects: ["Math", "Science", "English"], // Array inside an object
};

console.log(student.subjects[1]); // Output -> "Science"

Summary

In this section, you’ve learned about objects and arrays, two fundamental data structures in JavaScript. Objects allow you to store data in key-value pairs, making them ideal for modeling more complex data. Arrays are used to hold lists of values, allowing for easy data manipulation with various methods. Mastering objects and arrays will enable you to handle data more effectively in your JavaScript programs.