Arrays and objects are the most commonly used data structures in JavaScript.
They allow you to store multiple values and organize your data effectively.
Arrays
An array stores a list of values.
Values can be numbers, strings, objects, or even other arrays.
let numbers = [1, 2, 3, 4];
let fruits = ["apple", "banana", "orange"];Accessing array items:
console.log(fruits[0]); // apple
console.log(fruits[2]); // orangeUpdating array items:
fruits[1] = "kiwi";Array Methods
JavaScript includes many built-in methods.
let items = ["a", "b", "c"];
items.push("d"); // ["a", "b", "c", "d"]
items.pop(); // removes last item
items.shift(); // removes first item
items.unshift("z"); // adds to the beginningModern array helpers:
items.forEach(item => console.log(item));
let uppercased = items.map(item => item.toUpperCase());
let filtered = items.filter(item => item !== "b");Objects
Objects store data in key-value pairs.
let user = {
name: "Emre",
age: 30,
city: "Antalya"
};Accessing values:
console.log(user.name);
console.log(user['city']);Updating properties:
user.age = 31;
user.country = "Turkey";Nested Objects and Arrays
Objects can contain arrays and arrays can contain objects.
let product = {
title: "Phone",
price: 12000,
colors: ["black", "white"],
seller: {
name: "TechStore",
rating: 4.8
}
};Accessing nested values:
console.log(product.colors[1]); // white
console.log(product.seller.name); // TechStoreObject Methods
Objects can also contain functions.
let person = {
name: "Emre",
greet() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Hello, EmreDestructuring (ES6)
Destructuring allows you to extract values quickly.
let {name, city} = user;
console.log(name); // EmreArray destructuring:
let [first, second] = fruits;Spread Operator
let extended = [...numbers, 5, 6];
let clonedUser = {...user};Spread makes copying and merging easy.
Summary
In this lesson, you learned:
- How arrays store ordered lists
- Common array methods
- How objects store key-value pairs
- Nested objects and arrays
- Object methods and this keyword
- Destructuring and spread operator
In the next lesson, we will explore loops and iteration to work efficiently with lists of data.