Lesson 5 / 11

Arrays and Objects

Arrays

const courses = ["Python", "JavaScript", "SQL"];
courses.push("Java");
const webCourses = courses.filter(c => c !== "Python");
const upper = courses.map(c => c.toUpperCase());
const hasJava = courses.includes("Java");   // true

map, filter, and reduce are the three array methods you’ll reach for constantly — they transform data without writing manual loops, and none of them modify the original array; each returns a brand new one.

const scores = [90, 85, 78, 92];
const total = scores.reduce((sum, score) => sum + score, 0);
const average = total / scores.length;

reduce is the most flexible of the three but also the trickiest to read at first — it “reduces” an entire array down to one value by running an accumulator function over each item in turn, starting from the initial value you provide (0 above).

Objects

const student = {
  name: "Yash",
  course: "JavaScript",
  completedLessons: 4,
};
console.log(student.name);
student.completedLessons += 1;
console.log(student["course"]);   // bracket notation also works

Dot notation (student.name) and bracket notation (student["name"]) both work identically for a known key — but only bracket notation works when the key name is stored in a variable, which comes up constantly once you’re generating data dynamically.

Destructuring

const { name, course } = student;
const [first, second] = courses;

Destructuring pulls values straight out of an object or array into named variables in one line — you’ll see it everywhere in real codebases, including as a common way to accept multiple named parameters in a function signature, and constantly throughout frameworks like React.

The spread operator

const moreCourses = [...courses, "C++"];   // copies courses, then adds C++
const updatedStudent = { ...student, completedLessons: 10 };

... spreads the contents of an array or object into a new one — this is the standard way to create an updated copy of data without mutating the original, which matters a great deal in frameworks that expect you never to modify state directly.