JavaScript Lesson 8: Arrays
Arrays in JavaScript work similarly to Python lists but with different method names. Arrays are everywhere in JS development.
Creating Arrays
const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixed = ["Alice", 30, true, null];
const empty = [];
console.log(fruits[0]); // apple
console.log(fruits.length); // 3
console.log(fruits[fruits.length - 1]); // cherry (last)
Modifying Arrays
const arr = ["a", "b", "c"];
arr.push("d"); // add to end → ["a","b","c","d"]
arr.pop(); // remove last → ["a","b","c"]
arr.unshift("z"); // add to start → ["z","a","b","c"]
arr.shift(); // remove first → ["a","b","c"]
arr.splice(1, 1); // remove at index 1 → ["a","c"]
arr.splice(1, 0, "x"); // insert at index 1 → ["a","x","c"]
console.log(arr);
Searching Arrays
const nums = [10, 20, 30, 20, 40];
console.log(nums.indexOf(20)); // 1 (first occurrence)
console.log(nums.lastIndexOf(20)); // 3 (last occurrence)
console.log(nums.includes(30)); // true
console.log(nums.includes(99)); // false
console.log(nums.find(n => n > 25)); // 30
console.log(nums.findIndex(n => n > 25)); // 2
Copying and Combining
const a = [1, 2, 3];
const b = [4, 5, 6];
// Combine arrays
const combined = [...a, ...b]; // [1,2,3,4,5,6]
const concat = a.concat(b); // same
// Copy array
const copy = [...a]; // [1,2,3] (not a reference!)
const copy2 = a.slice(); // same
// Slice (extract portion)
console.log(a.slice(1, 3)); // [2, 3]
🏋️ Practice Task
Create an array of 5 student names. Write code to: (1) add a new student at the end, (2) remove the first student, (3) check if “Alice” is in the list, (4) find the index of a specific name, (5) print all names with their position numbers.
💡 Hint: Use push, shift, includes, indexOf. For position numbers, use forEach with the index parameter.