Arrays & Objects
Topic: Arrays & Objects
Concepts Covered: Creation, access, array methods (push,map), object properties
Arrays
Section titled “Arrays”Arrays are ordered collections of values, perfect for storing lists of data.
Creating Arrays
Section titled “Creating Arrays”// Empty arraylet emptyArray = [];
// Array with initial valueslet fruits = ["Apple", "Banana", "Cherry"];let numbers = [1, 2, 3, 4, 5];let mixed = ["string", 42, true, null];Accessing Array Elements
Section titled “Accessing Array Elements”Arrays use zero-based indexing:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // "Apple" (first element)console.log(fruits[1]); // "Banana"console.log(fruits[2]); // "Cherry"console.log(fruits[3]); // undefined (doesn't exist)
// Get array lengthconsole.log(fruits.length); // 3Modifying Arrays
Section titled “Modifying Arrays”let fruits = ["Apple", "Banana"];
// Add elementsfruits[2] = "Cherry"; // Add at specific indexfruits.push("Date"); // Add to endfruits.unshift("Elderberry"); // Add to beginning
console.log(fruits); // ["Elderberry", "Apple", "Banana", "Cherry", "Date"]
// Remove elementslet last = fruits.pop(); // Remove and return last elementlet first = fruits.shift(); // Remove and return first element
console.log(last); // "Date"console.log(first); // "Elderberry"Essential Array Methods
Section titled “Essential Array Methods”Adding/Removing Elements
Section titled “Adding/Removing Elements”let fruits = ["Apple", "Banana", "Cherry"];
// push() - add to endfruits.push("Date", "Fig");console.log(fruits); // ["Apple", "Banana", "Cherry", "Date", "Fig"]
// pop() - remove from endlet removed = fruits.pop();console.log(removed); // "Fig"
// unshift() - add to beginningfruits.unshift("Elderberry");console.log(fruits); // ["Elderberry", "Apple", "Banana", "Cherry", "Date"]
// shift() - remove from beginninglet first = fruits.shift();console.log(first); // "Elderberry"Finding Elements
Section titled “Finding Elements”let fruits = ["Apple", "Banana", "Cherry"];
// indexOf() - find index of elementlet index = fruits.indexOf("Banana");console.log(index); // 1
// includes() - check if element existsconsole.log(fruits.includes("Apple")); // trueconsole.log(fruits.includes("Grape")); // falseModifying Arrays
Section titled “Modifying Arrays”let months = ["Jan", "March", "Jun", "Aug"];
// splice() - add/remove elements at specific positionmonths.splice(1, 0, "Feb"); // Insert "Feb" at index 1console.log(months); // ["Jan", "Feb", "March", "Jun", "Aug"]
months.splice(4, 1, "July"); // Replace 1 element at index 4console.log(months); // ["Jan", "Feb", "March", "Jun", "July"]
// slice() - create new array with portion of originallet firstThree = months.slice(0, 3);console.log(firstThree); // ["Jan", "Feb", "March"]console.log(months); // Original unchanged: ["Jan", "Feb", "March", "Jun", "July"]Looping Through Arrays
Section titled “Looping Through Arrays”Traditional For Loop
Section titled “Traditional For Loop”let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) { console.log(`${i}: ${fruits[i]}`);}For…Of Loop (Modern)
Section titled “For…Of Loop (Modern)”let fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) { console.log(fruit);}forEach Method
Section titled “forEach Method”let fruits = ["Apple", "Banana", "Cherry"];
fruits.forEach(function (fruit, index) { console.log(`${index}: ${fruit}`);});
// Arrow function versionfruits.forEach((fruit, index) => { console.log(`${index}: ${fruit}`);});Higher-Order Array Methods
Section titled “Higher-Order Array Methods”map() - Transform Each Element
Section titled “map() - Transform Each Element”let numbers = [1, 2, 3, 4, 5];
// Square each numberlet squared = numbers.map(function (num) { return num * num;});console.log(squared); // [1, 4, 9, 16, 25]
// Arrow function versionlet doubled = numbers.map((num) => num * 2);console.log(doubled); // [2, 4, 6, 8, 10]
// Transform stringslet names = ["alice", "bob", "charlie"];let capitalized = names.map((name) => name.toUpperCase());console.log(capitalized); // ["ALICE", "BOB", "CHARLIE"]Practical Array Functions
Section titled “Practical Array Functions”// Generate multiplication tablefunction generateMultiples(number) { const multiples = [];
for (let i = 1; i <= 12; i++) { multiples.push(number * i); }
return multiples;}
console.log(generateMultiples(3)); // [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36]
// Square array elementsfunction squareArray(numbers) { return numbers.map((num) => num ** 2);}
console.log(squareArray([1, 2, 3, 4])); // [1, 4, 9, 16]Objects
Section titled “Objects”Objects are collections of key-value pairs, perfect for storing related data.
Creating Objects
Section titled “Creating Objects”// Object literal syntaxlet person = { firstName: "John", lastName: "Doe", age: 30, isStudent: false,};
// Empty objectlet emptyObject = {};Accessing Object Properties
Section titled “Accessing Object Properties”Dot Notation
Section titled “Dot Notation”let person = { firstName: "John", lastName: "Doe", age: 30,};
console.log(person.firstName); // "John"console.log(person.age); // 30Bracket Notation
Section titled “Bracket Notation”let person = { firstName: "John", lastName: "Doe", "favorite color": "blue", // Property with space};
console.log(person["firstName"]); // "John"console.log(person["favorite color"]); // "blue"
// Dynamic property accesslet property = "age";console.log(person[property]); // Access using variableModifying Objects
Section titled “Modifying Objects”let person = { firstName: "John", lastName: "Doe",};
// Add new propertiesperson.age = 30;person["email"] = "john@example.com";
// Modify existing propertiesperson.firstName = "Jane";
// Delete propertiesdelete person.age;
console.log(person); // { firstName: "Jane", lastName: "Doe", email: "john@example.com" }Object Methods
Section titled “Object Methods”let student = { firstName: "Alice", lastName: "Johnson", grade: 85,
// Method using function keyword getFullName: function () { return `${this.firstName} ${this.lastName}`; },
// Method using shorthand syntax getGradeStatus() { return this.grade >= 60 ? "Pass" : "Fail"; },};
console.log(student.getFullName()); // "Alice Johnson"console.log(student.getGradeStatus()); // "Pass"The this Keyword
Section titled “The this Keyword”this refers to the object that the method belongs to:
let calculator = { value: 0,
add(number) { this.value += number; return this; // Return this for chaining },
subtract(number) { this.value -= number; return this; },
getValue() { return this.value; },};
// Method chaininglet result = calculator.add(10).subtract(3).getValue();console.log(result); // 7Object Utility Methods
Section titled “Object Utility Methods”let person = { name: "John", age: 30, city: "New York",};
// Get all keyslet keys = Object.keys(person);console.log(keys); // ["name", "age", "city"]
// Get all valueslet values = Object.values(person);console.log(values); // ["John", 30, "New York"]
// Get key-value pairslet entries = Object.entries(person);console.log(entries); // [["name", "John"], ["age", 30], ["city", "New York"]]Looping Through Objects
Section titled “Looping Through Objects”For…In Loop
Section titled “For…In Loop”let person = { name: "John", age: 30, city: "New York",};
for (let key in person) { console.log(`${key}: ${person[key]}`);}// Output:// name: John// age: 30// city: New YorkUsing Object Methods
Section titled “Using Object Methods”let person = { name: "John", age: 30, city: "New York",};
// Loop through keysObject.keys(person).forEach((key) => { console.log(`${key}: ${person[key]}`);});
// Loop through valuesObject.values(person).forEach((value) => { console.log(value);});
// Loop through entriesObject.entries(person).forEach(([key, value]) => { console.log(`${key}: ${value}`);});Nested Objects and Arrays
Section titled “Nested Objects and Arrays”let student = { name: "Alice", grades: [85, 92, 78, 96], address: { street: "123 Main St", city: "Boston", zip: "02101", },
getAverageGrade() { let sum = this.grades.reduce((total, grade) => total + grade, 0); return sum / this.grades.length; },};
console.log(student.address.city); // "Boston"console.log(student.grades[0]); // 85console.log(student.getAverageGrade()); // 87.75Practical Examples
Section titled “Practical Examples”Student Management System
Section titled “Student Management System”function createStudent(firstName, lastName, grades = []) { return { firstName, lastName, grades,
addGrade(grade) { this.grades.push(grade); },
getAverage() { if (this.grades.length === 0) return 0; let sum = this.grades.reduce((total, grade) => total + grade, 0); return sum / this.grades.length; },
getFullName() { return `${this.firstName} ${this.lastName}`; }, };}
let student1 = createStudent("John", "Doe", [85, 92, 78]);student1.addGrade(88);console.log(`${student1.getFullName()}: ${student1.getAverage()}`);Inventory System
Section titled “Inventory System”let inventory = [ { id: 1, name: "Laptop", price: 999, quantity: 5 }, { id: 2, name: "Mouse", price: 25, quantity: 20 }, { id: 3, name: "Keyboard", price: 75, quantity: 15 },];
// Find item by IDfunction findItemById(id) { return inventory.find((item) => item.id === id);}
// Update quantityfunction updateQuantity(id, newQuantity) { let item = findItemById(id); if (item) { item.quantity = newQuantity; }}
// Calculate total inventory valuefunction calculateTotalValue() { return inventory.reduce((total, item) => { return total + item.price * item.quantity; }, 0);}
console.log(calculateTotalValue()); // Total value of all itemsBest Practices
Section titled “Best Practices”- Use descriptive property names:
firstNameinstead offn - Use dot notation when possible: More readable than bracket notation
- Group related data in objects: Better organization
- Use methods for object behavior: Keep data and behavior together
- Use
constfor arrays/objects: The reference won’t change (contents can)
Common Pitfalls
Section titled “Common Pitfalls”- Mutating arrays/objects unintentionally: Use methods that return new arrays
- Confusing array methods:
pushmodifies original,concatreturns new - Wrong
thiscontext: Arrow functions don’t have their ownthis - Accessing non-existent properties: Results in
undefined
Key Takeaways
Section titled “Key Takeaways”- Arrays: Use for ordered lists of data
- Objects: Use for structured data with named properties
- Array methods:
push,pop,map,forEachare essential - Object access: Use dot notation or bracket notation
thiskeyword: Refers to the object in method context- Iteration: Multiple ways to loop through arrays and objects
Practice Exercises
Section titled “Practice Exercises”- Create a shopping cart system with add/remove/total functionality
- Build a grade book that calculates averages and letter grades
- Make a simple contact management system
- Create a library system to track books and borrowers
- Build a simple inventory management system