How `this` behaves in JavaScript
April 24, 2025
1 min
...
)Use it to expand values β most often used in arrays, objects, or function calls.
const a = [1, 2];const b = [...a, 3, 4];console.log(b); // [1, 2, 3, 4]
const user = { name: "Daniel" };const fullUser = { ...user, age: 30 };console.log(fullUser); // { name: "Daniel", age: 30 }
const nums = [1, 2, 3];Math.max(...nums); // 3
...
)Use it to collect values into an array or object β often used in function parameters or object destructuring.
function sum(...args) {return args.reduce((a, b) => a + b, 0);}sum(1, 2, 3); // 6
const [first, ...rest] = [10, 20, 30];console.log(first); // 10console.log(rest); // [20, 30]
const user = { name: "Daniel", age: 30, city: "HCM" };const { name, ...details } = user;console.log(name); // "Daniel"console.log(details); // { age: 30, city: "HCM" }
Same syntax (...
), but usage depends on context:
Alright, letβs hit you with a quick 3-question quiz focused purely on spread/rest operators! π§ β¨
const arr = [1, 2, 3];const newArr = [...arr, 4];console.log(newArr);
A. [1, 2, 3]
B. [4, 1, 2, 3]
C. [1, 2, 3, 4]
D. undefined
rest
?const [a, b, ...rest] = [10, 20, 30, 40];console.log(rest);
A. 30
B. [30, 40]
C. [20, 30, 40]
D. undefined
function greet(greeting, ...names) {return `${greeting}, ${names.join(" and ")}`;}console.log(greet("Hello", "Alice", "Bob", "Carol"));
A. "Hello, Alice"
B. "Hello, Alice and Bob"
C. "Hello, Alice and Bob and Carol"
D. "Hello, [object Object]"
Drop your answers and Iβll let you know how you did! π―
Quick Links
Legal Stuff
Social Media