Arrays and Objects
Arrays and objects are fundamental structures for organizing data. Let's master them!
Arrays (Lists)
An array is an ordered list of values:
javascript
const fruits = ["apple", "banana", "orange"];const numbers = [1, 2, 3, 4, 5];const mixed = ["text", 42, true, null];Accessing Elements
Indices start at 0!
javascript
const fruits = ["apple", "banana", "orange"]; console.log(fruits[0]); // "apple"console.log(fruits[1]); // "banana"console.log(fruits[2]); // "orange"console.log(fruits[3]); // undefined (doesn't exist) // Last elementconsole.log(fruits[fruits.length - 1]); // "orange"Modifying Arrays
javascript
const fruits = ["apple", "banana"]; // Add to endfruits.push("orange"); // ["apple", "banana", "orange"] // Remove from endfruits.pop(); // ["apple", "banana"] // Add to beginningfruits.unshift("grape"); // ["grape", "apple", "banana"] // Remove from beginningfruits.shift(); // ["apple", "banana"] // Change specific elementfruits[0] = "strawberry"; // ["strawberry", "banana"]Useful Array Methods
javascript
const numbers = [3, 1, 4, 1, 5, 9, 2, 6]; // Lengthnumbers.length; // 8 // Findnumbers.includes(5); // truenumbers.indexOf(4); // 2 (position) // Sortnumbers.sort((a, b) => a - b); // [1, 1, 2, 3, 4, 5, 6, 9] // Reversenumbers.reverse(); // [9, 6, 5, 4, 3, 2, 1, 1] // Slicenumbers.slice(0, 3); // first 3 elements // Join as string["a", "b", "c"].join("-"); // "a-b-c"Iteration Methods
javascript
const numbers = [1, 2, 3, 4, 5]; // forEach - execute for each itemnumbers.forEach(num => { console.log(num * 2);}); // map - transform and create new arrayconst doubled = numbers.map(num => num * 2);// [2, 4, 6, 8, 10] // filter - filter itemsconst greaterThan2 = numbers.filter(num => num > 2);// [3, 4, 5] // find - find first that satisfies conditionconst found = numbers.find(num => num > 3);// 4 // reduce - reduce to one valueconst sum = numbers.reduce((acc, num) => acc + num, 0);// 15Objects
Objects store data in key-value pairs:
javascript
const person = { name: "John", age: 25, city: "New York", active: true};Accessing Properties
javascript
// Dot notationconsole.log(person.name); // "John"console.log(person.age); // 25 // Bracket notationconsole.log(person["name"]); // "John" // Useful with variablesconst prop = "city";console.log(person[prop]); // "New York"Modifying Objects
javascript
const person = { name: "John", age: 25 }; // Modifyperson.age = 26; // Addperson.email = "john@email.com"; // Removedelete person.email;Object Methods
javascript
const person = { name: "John", age: 25 }; // KeysObject.keys(person); // ["name", "age"] // ValuesObject.values(person); // ["John", 25] // EntriesObject.entries(person); // [["name", "John"], ["age", 25]] // Check if exists"name" in person; // trueperson.hasOwnProperty("email"); // falseObjects with Methods
Objects can have functions:
javascript
const person = { name: "John", age: 25, introduce() { return `Hi, my name is ${this.name}!`; }, haveBirthday() { this.age++; return `Now I'm ${this.age} years old!`; }}; console.log(person.introduce()); // "Hi, my name is John!"console.log(person.haveBirthday()); // "Now I'm 26 years old!"this refers to the object itself.
Arrays of Objects
Super common in practice:
javascript
const users = [ { id: 1, name: "Anna", age: 28 }, { id: 2, name: "Bruno", age: 35 }, { id: 3, name: "Carla", age: 22 }]; // Find by idconst user = users.find(u => u.id === 2);// { id: 2, name: "Bruno", age: 35 } // Filter by ageconst adults = users.filter(u => u.age >= 25);// [{ id: 1, name: "Anna"... }, { id: 2, name: "Bruno"... }] // Extract only namesconst names = users.map(u => u.name);// ["Anna", "Bruno", "Carla"] // Sum agesconst sumAges = users.reduce((acc, u) => acc + u.age, 0);// 85Destructuring
Extract values elegantly:
Arrays
javascript
const colors = ["red", "green", "blue"]; const [first, second, third] = colors;console.log(first); // "red"console.log(second); // "green"Objects
javascript
const person = { name: "John", age: 25, city: "NYC" }; const { name, age } = person;console.log(name); // "John"console.log(age); // 25In function parameters
javascript
function displayPerson({ name, age }) { console.log(`${name} is ${age} years old`);} displayPerson({ name: "Anna", age: 30 });Spread Operator (...)
Copy arrays
javascript
const original = [1, 2, 3];const copy = [...original];Join arrays
javascript
const a = [1, 2];const b = [3, 4];const joined = [...a, ...b]; // [1, 2, 3, 4]Copy objects
javascript
const original = { a: 1, b: 2 };const copy = { ...original };const modified = { ...original, b: 10, c: 3 };// { a: 1, b: 10, c: 3 }Exercise: Todo List
javascript
const tasks = [ { id: 1, title: "Study JS", completed: true }, { id: 2, title: "Do exercises", completed: false }, { id: 3, title: "Create project", completed: false }]; // Add taskfunction addTask(title) { const newTask = { id: tasks.length + 1, title, completed: false }; tasks.push(newTask); return newTask;} // Mark as completedfunction completeTask(id) { const task = tasks.find(t => t.id === id); if (task) { task.completed = true; return task; } return null;} // List pendingfunction listPending() { return tasks.filter(t => !t.completed);} // TestaddTask("Review code");completeTask(2);console.log(listPending());Summary
- ✅ Arrays: ordered lists with indices
- ✅
map,filter,find,reduceto transform - ✅ Objects: key-value pairs
- ✅
thisreferences the object itself - ✅ Destructuring extracts values elegantly
- ✅ Spread
...copies and combines
In the next lesson, we'll connect JavaScript to HTML with the DOM! 🚀