#javascript #tutorial #beginner

Day 4: Objects & Arrays

Day 4: Structuring Data

Variables are great for single values, but what if you have a list of items or a complex entity like a “User”? That’s where Arrays and Objects come in.

1. Arrays (Lists)

An ordered collection of items.

const fruits = ["Apple", "Banana", "Cherry"];

console.log(fruits[0]); // Apple
console.log(fruits.length); // 3

Common Array Methods

  • push(): Add to end.
  • pop(): Remove from end.
  • map(): Transform each item (returns new array).
  • filter(): Keep specific items (returns new array).
const numbers = [1, 2, 3, 4, 5];

// Multiply by 2
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// Keep only evens
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]

2. Objects (Key-Value Pairs)

Used to describe a specific thing with properties.

const user = {
    name: "Jack",
    age: 30,
    isAdmin: true,
    greet: function() {
        console.log("Hello!");
    }
};

console.log(user.name); // Jack (Dot notation)
console.log(user["age"]); // 30 (Bracket notation)

user.greet(); // Hello!

Modifying Objects

user.email = "jack@example.com"; // Add new property
user.age = 31; // Update existing

Array of Objects

This is how almost all real-world data (like from an API) looks.

const products = [
    { id: 1, name: "Laptop", price: 1000 },
    { id: 2, name: "Mouse", price: 25 },
    { id: 3, name: "Keyboard", price: 75 }
];

// Find expensive items
const expensive = products.filter(p => p.price > 50);
console.log(expensive); // Laptop, Keyboard

Homework for Day 4:

  1. Create an array of todo objects (e.g., { text: "Buy milk", done: false }).
  2. Write a function that takes this array and returns only the items where done is true.
  3. Add a new task to the list using push.

Day 5: We finally touch the web page with the DOM!