Chapter 4: Objects and Arrays
Welcome back to "Mastering JavaScript"! In Chapter 3, we explored functions and scope, building a strong foundation for our JavaScript journey. Now, let's dive into objects and arrays, two fundamental data structures that you'll use frequently in your JavaScript programs.
4.1 Understanding Objects
Objects in JavaScript are collections of key-value pairs. They are used to store data and represent real-world entities. Each key is a string, and the value can be of any data type, including another object or an array.
Let's create a simple object to represent a person:
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
isStudent: true
};
// Accessing object properties
console.log(person.firstName); // Output: John
console.log(person["lastName"]); // Output: Doe
// Adding a new property
person.email = "john.doe@example.com";
console.log(person.email); // Output: john.doe@example.com
// Updating a property
person.age = 31;
console.log(person.age); // Output: 31
4.2 Working with Arrays
Arrays are ordered lists of values. They are incredibly versatile and can store any data type, including other arrays or objects.
Here's how you can create and manipulate arrays:
// Creating an array
let colors = ["red", "green", "blue"];
// Accessing array elements
console.log(colors[0]); // Output: red
// Adding elements to an array
colors.push("yellow");
console.log(colors); // Output: ["red", "green", "blue", "yellow"]
// Removing elements from an array
colors.pop();
console.log(colors); // Output: ["red", "green", "blue"]
// Updating array elements
colors[1] = "purple";
console.log(colors); // Output: ["red", "purple", "blue"]
4.3 Common Methods for Objects and Arrays
JavaScript provides several built-in methods for working with objects and arrays. Here are some of the most commonly used ones:
Object Methods:
Object.keys(obj)
: Returns an array of an object's keys.Object.values(obj)
: Returns an array of an object's values.Object.entries(obj)
: Returns an array of key-value pairs.
let car = {
brand: "Toyota",
model: "Corolla",
year: 2021
};
console.log(Object.keys(car)); // Output: ["brand", "model", "year"]
console.log(Object.values(car)); // Output: ["Toyota", "Corolla", 2021]
console.log(Object.entries(car)); // Output: [["brand", "Toyota"], ["model", "Corolla"], ["year", 2021]]
Array Methods:
forEach(callback)
: Executes a callback function for each element.map(callback)
: Creates a new array with the results of calling a callback function on every element.filter(callback)
: Creates a new array with elements that pass a test defined by a callback function.find(callback)
: Returns the first element that passes a test defined by a callback function.
let numbers = [1, 2, 3, 4, 5];
// forEach
numbers.forEach(num => console.log(num * 2)); // Output: 2, 4, 6, 8, 10
// map
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
// filter
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4]
// find
let firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // Output: 2
4.4 Practical Examples
Let's combine what we've learned about objects and arrays in a practical example. We'll create an array of objects representing a simple to-do list.
let todos = [
{ id: 1, task: "Learn JavaScript", completed: false },
{ id: 2, task: "Build a project", completed: false },
{ id: 3, task: "Apply for jobs", completed: false }
];
// Add a new to-do item
todos.push({ id: 4, task: "Prepare for interviews", completed: false });
// Mark the first task as completed
todos[0].completed = true;
// Filter completed tasks
let completedTasks = todos.filter(todo => todo.completed);
console.log(completedTasks); // Output: [{ id: 1, task: "Learn JavaScript", completed: true }]
In this chapter, we covered the basics of objects and arrays in JavaScript. You learned how to create and manipulate objects, work with arrays, and use common methods to make your code more efficient. Understanding these data structures is crucial as they are the building blocks for most JavaScript applications.
In the next chapter, we'll explore advanced array methods and dive deeper into object manipulation.
Happy coding!