JS JavaScript

JavaScript: Objects & Arrays

What you will learn

How to create and manipulate objects (key-value pairs) and arrays (ordered lists).

Objects

const person = {
    name: "Alice",
    age: 25,
    greet() { return `Hi, I'm ${this.name}`; }\n};
console.log(person.name);  // "Alice"  (dot notation)
console.log(person["age"]); // 25 (bracket notation)

Arrays

const fruits = ["apple", "banana", "cherry"];
fruits.push("date");       // add to end
fruits.pop();              // remove from end
fruits.unshift("apricot"); // add to start
fruits.shift();            // remove from start
fruits.length;             // 3

Arrays are zero-indexed: fruits[0] gives the first element.

Common array methods

const nums = [1, 2, 3, 4];
nums.map(n => n * 2);       // [2, 4, 6, 8]
nums.filter(n => n > 2);    // [3, 4]
nums.reduce((a, b) => a + b); // 10
nums.find(n => n > 2);      // 3 (first match)

Quick check below!