Web Development · Module 5 · Lesson 41 min read

Arrays & Objects

Arrays: ordered lists

JavaScript
const fruits = ["apple", "banana"];
fruits.push("mango");     // add to end
fruits.pop();             // remove from end
fruits.unshift("kiwi");   // add to start
fruits.includes("apple"); // true
fruits.indexOf("banana"); // 2
fruits.length;            // 3

Objects: key → value

JavaScript
const user = { name: "Ana", age: 25, skills: ["JS", "CSS"] };
user.age = 26;          // update
user.city = "Pokhara";  // add
delete user.city;       // remove
user["name"];           // bracket access for dynamic keys

Loop with Object.keys(user), Object.values(user) or Object.entries(user).

Destructuring and spread (used everywhere in modern JS)

JavaScript
const { name, age } = user;           // pull out properties
const [first, second] = fruits;       // pull out items
const copy = { ...user, age: 30 };    // copy and override
const all = [...fruits, "grape"];     // copy and add

Spread creates a shallow copy; nested objects are still shared. Use structuredClone(obj) for a deep copy.

JSON

The text format APIs use: JSON.stringify(obj) turns an object into a string, and JSON.parse(text) turns a string back into an object.

⚠️ Objects and arrays are copied by reference: const b = a means both names point to the same data.

Example

JavaScript
const user = { name: "Ana", age: 25, skills: ["JS", "CSS"] };

const { name, ...rest } = user;
console.log(name, rest);              // Ana { age: 25, skills: [...] }

const updated = { ...user, age: 26 }; // new object, original unchanged
console.log(user.age, updated.age);   // 25 26

for (const [key, value] of Object.entries(user)) {
  console.log(key, "→", value);
}

const text = JSON.stringify(updated);
console.log(text);                    // {"name":"Ana","age":26,"skills":["JS","CSS"]}
console.log(JSON.parse(text).skills[0]);   // JS