Module 5: Arrays, Objects, and Collections
Destructuring, Spread, and Rest
Extract values and copy or combine arrays and objects with modern syntax.
Destructuring extracts values from arrays or properties from objects into bindings.
const point = [12, 7];
const [x, y] = point;
const course = { title: "JavaScript", level: "Beginner" };
const { title, level } = course;
You can provide default values, rename object properties, and skip array elements. A default applies when the value is undefined, not when it is null.
const { duration = 30, title: courseTitle } = course;
Spread syntax#
Spread expands an iterable into individual values or copies enumerable properties into a new object:
const first = [1, 2];
const combined = [...first, 3, 4];
const updatedCourse = { ...course, level: "Intermediate" };
Later object properties override earlier ones when names collide. Spreading is shallow, so nested objects remain shared by reference.
Rest syntax#
Rest collects remaining items into an array or object:
const [head, ...tail] = [10, 20, 30];
const { title: name, ...otherDetails } = course;
Rest parameters in function signatures use the same ... token but gather function arguments.
Practice#
Write a function that takes a first argument and an arbitrary number of remaining tags. Use rest parameters to collect tags, then return a new object that includes the first argument and its tags.