Spread, Rest, and Template Literals
Three dots (...) spread or collect values depending on context. Backtick strings embed variables directly and support multi-line text.
Spread (right side) expands arrays and objects. Rest (left side / parameters) collects remaining items. Template literals use backticks and $ for clean string interpolation.
EXERCISE
1The Spread Operator: Unpacking Arrays and Objects
The three dots (...) spread an array or object into individual elements. It is used for copying, merging, and passing array elements as function arguments.
Three dots spread a collection out into its individual items. Where you write it decides what that means, and this exercise is about the spreading half.
const numbers = [1, 2, 3];
console.log(Math.max(numbers)); // NaN
console.log(Math.max(...numbers)); // 3
Math.max takes separate arguments, not an array. The spread hands it 1, 2, 3 as three arguments rather than one array.
Combining arrays:
const fruits = ["apple", "banana"];
const vegetables = ["carrot", "spinach"];
const produce = [...fruits, ...vegetables];
console.log(produce); // ["apple", "banana", "carrot", "spinach"]
The result is a new array. Neither original is modified, which is the difference from push, and you can put items around the spread freely:
const withExtras = ["first", ...fruits, "last"];
console.log(withExtras); // ["first", "apple", "banana", "last"]
Copying an array, which is the most common use of all:
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]
Without the spread, const copy = original would give two names for one array and push would change both.
The same syntax works on objects:
const defaults = { theme: "light", fontSize: 14 };
const userPrefs = { fontSize: 16 };
const settings = { ...defaults, ...userPrefs };
console.log(settings); // { theme: "light", fontSize: 16 }
Later properties win, which is what makes this the standard way to apply overrides. Reversing the order would let the defaults overwrite the user's choice.
The copy is shallow, exactly as in the objects lesson:
const user = { name: "Ali", address: { city: "London" } };
const copy = { ...user };
copy.address.city = "Paris";
console.log(user.address.city); // "Paris"
The top level is independent; address is a reference that both objects share. This catches people constantly, because the spread genuinely does copy and it is easy to assume it copies all the way down.
It is worth being precise about what the spread actually does, because "it copies the array" is close enough to be useful and wrong often enough to cause bugs. The spread reads each element of the source and places that same value into the new collection. For numbers and strings, which are copied by value, the result is fully independent. For objects and arrays, which are held by reference, what gets placed in the new collection is the reference, so both collections end up pointing at the same underlying object.
That is why the array of objects case behaves the way it does: the array itself is new and can be pushed to without affecting the original, while the objects inside it are shared and can be mutated through either one. When you need independence all the way down, structuredClone walks every level; when you only need to add or remove elements, the spread is exactly right and considerably cheaper.
EXERCISE
2The Rest Operator: Collecting Everything Else
Rest looks identical to spread (three dots), but it does the opposite: instead of unpacking, it packs remaining elements into an array or object.
The same three dots in a parameter list do the opposite job: instead of spreading a collection out, they collect loose values into an array.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
console.log(sum()); // 0
numbers is a real array, so reduce and every other array method work on it. The function accepts any number of arguments without declaring them.
Which one you get is decided by position. In a call or a literal, the dots spread. In a parameter list or on the left of an assignment, they collect.
function show(...args) { // collects
console.log(args);
}
show(...[1, 2, 3]); // spreads
Rest must come last, and takes only what is left over:
function describe(first, second, ...others) {
return first + ", " + second + ", plus " + others.length + " more";
}
console.log(describe("a", "b", "c", "d")); // "a, b, plus 2 more"
Putting it anywhere else is a syntax error, because "everything else" has no meaning in the middle of a list.
On objects, rest collects the properties you did not name:
const user = { id: 1, name: "Sara", password: "secret", role: "admin" };
const { password, ...safe } = user;
console.log(safe); // { id: 1, name: "Sara", role: "admin" }
This is the standard way to remove a field without mutating the original. delete user.password would change the object everyone else is holding; this builds a new one and leaves the original intact.
Rest is not arguments:
function old() {
console.log(arguments.length); // works
console.log(arguments.map); // undefined
}
function modern(...args) {
console.log(args.length); // works
console.log(args.map((x) => x)); // works
}
arguments is an array-like object that older code uses for the same purpose. It has a length and indexes but none of the array methods, and it does not exist at all inside an arrow function. Rest parameters give you a genuine array and work everywhere.
EXERCISE
3Template Literals: Clean String Building
Template literals use backticks instead of quotes. They let you embed variables directly in strings, write multi-line strings, and never worry about string concatenation again.
Template literals are strings written with backticks. They solve two problems that quoted strings handle badly: inserting values, and spanning lines.
const name = "Sara";
const age = 28;
const msg = "Hello, " + name + "! You are " + age + " years old.";
Count what has to be right: four + operators, and a trailing space inside one fragment and a leading space inside another. Miss one and the output reads Hello,Sara. The quotes and the operators take up more room on the line than the sentence does.
const msg = `Hello, ${name}! You are ${age} years old.`;
console.log(msg); // "Hello, Sara! You are 28 years old."
${name} marks a hole to be filled. The spacing is now literally what you see, because the spaces are part of the string rather than something you have to remember to include.
Anything that produces a value can go between the braces:
const price = 250;
const qty = 3;
console.log(`Total: ${price * qty}`); // "Total: 750"
console.log(`Type: ${qty > 2 ? "bulk" : "single"}`); // "Type: bulk"
console.log(`Name: ${name.toUpperCase()}`); // "Name: SARA"
Expressions, not statements. An if will not fit there, which is why the conditional operator appears so often inside template literals.
Line breaks are kept:
const html = `
<div>
<h1>${name}</h1>
</div>
`;
console.log(html);
With quotes this needs \n escapes or concatenation, and the shape of the output is invisible in the source. Here what you see is what gets printed, including the leading newline after the opening backtick and the spaces before the closing one, which are part of the string whether you meant them or not.
One detail that catches everyone:
const wrong = "Hello, ${name}";
const right = `Hello, ${name}`;
console.log(wrong); // "Hello, ${name}"
console.log(right); // "Hello, Sara"
${} means nothing inside single or double quotes. It is four ordinary characters, no substitution happens, and no error is raised. When a template appears verbatim in your output, the quotes are the first thing to check.
Pro Tip: Never build HTML or SQL from a template literal with untrusted values in it. The substitution is plain text insertion with no escaping, which is precisely how injection bugs are written.
