Week 3
3.5 JavaScript Objects & Arrays
Week 3
3.5 JavaScript Objects & Arrays
JavaScript Objects & Arrays
JavaScript Objects and Arrays are data structures that allow us to store, organize, and manipulate data efficiently. Without them, managing complex data in applications would be messy!
In this section, we’ll cover:
1, Creating objects ({ key: value })
2, Object methods (this keyword)
3, Arrays & array methods (push, pop, map, filter, reduce, etc.)
4, Object destructuring & spread/rest operators
Let’s dive in!
1. JavaScript Objects
An object is a collection of related data stored in key-value pairs. It’s like a dictionary that lets us label each piece of data!
const person = {
name: "Alice",
age: 25,
isStudent: true
};
console.log(person.name); // Output: Alice
console.log(person.age); // Output: 25
Keys (name, age, isStudent) are always strings
Values can be any data type (string, number, boolean, etc.)
Objects make it easy to structure data in a readable way!
2. Object Methods – Functions Inside Objects
Objects can have methods (functions stored inside them).
const car = {
brand: "Tesla",
model: "Model S",
speed: 120,
drive: function() {
console.log("The car is moving at " + this.speed + " km/h");
}
};
car.drive(); // Output: The car is moving at 120 km/h
Methods are functions stored in an object
Use this to refer to properties inside the same object
Without this, JavaScript wouldn’t know which object we are talking about!
3. JavaScript Arrays – Storing Multiple Values
An array is like a list where you can store multiple values in a single variable.
const fruits = ["Apple", "Banana", "Grape"];
console.log(fruits[0]); // Output: Apple
console.log(fruits.length); // Output: 3
Arrays store values in order, starting from index 0
Use fruits.length to find the number of items
4. Array Methods
JavaScript provides powerful methods to manipulate arrays easily.
const animals = ["Dog", "Cat"];
animals.push("Monkey");
console.log(animals); // Output: ["Dog", "Cat", "Monkey"]
animals.pop();
console.log(animals); // Output: ["Dog", "Cat"]
animals.shift();
console.log(animals); // Output: ["Cat"]
animals.unshift("Elephant");
console.log(animals); // Output: ["Elephant", "Cat"]
5. Object Destructuring
JavaScript provides shortcuts to work with objects and arrays easily!
Instead of writing:
const user = { name: "Alice", age: 25 };
const userName = user.name;
const userAge = user.age;
Use destructuring:
const { name, age } = user;
console.log(name, age); // Output: Alice 25
Destructuring makes code cleaner!
Final Recap!
Objects store data as { key: value }
Methods are functions inside objects (this refers to the object)
Arrays store lists of values and have powerful methods
Destructuring extracts values easily from objects
Next up: JavaScript DOM Manipulation!