HomeAbout Me

πŸ” JavaScript Destructuring

By Daniel Nguyen
Published in Javascript
April 06, 2025
1 min read

πŸ”Ή Spread Operator (...)

Use it to expand values β€” most often used in arrays, objects, or function calls.

βœ… Examples:

1. In Arrays:

const a = [1, 2];
const b = [...a, 3, 4];
console.log(b); // [1, 2, 3, 4]

2. In Objects:

const user = { name: "Daniel" };
const fullUser = { ...user, age: 30 };
console.log(fullUser); // { name: "Daniel", age: 30 }

3. In Function Calls:

const nums = [1, 2, 3];
Math.max(...nums); // 3

πŸ”Έ Rest Operator (...)

Use it to collect values into an array or object β€” often used in function parameters or object destructuring.

βœ… Examples:

1. In Function Parameters:

function sum(...args) {
return args.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3); // 6

2. In Array Destructuring:

const [first, ...rest] = [10, 20, 30];
console.log(first); // 10
console.log(rest); // [20, 30]

3. In Object Destructuring:

const user = { name: "Daniel", age: 30, city: "HCM" };
const { name, ...details } = user;
console.log(name); // "Daniel"
console.log(details); // { age: 30, city: "HCM" }

⚠️ Quick Tip:

Same syntax (...), but usage depends on context:

  • Spread: on the right side β†’ expands things
  • Rest: on the left side β†’ gathers things

Alright, let’s hit you with a quick 3-question quiz focused purely on spread/rest operators! 🧠✨


Q1. What does this code print?

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


Q2. What is the value of rest?

const [a, b, ...rest] = [10, 20, 30, 40];
console.log(rest);

A. 30
B. [30, 40]
C. [20, 30, 40]
D. undefined


Q3. What does this log?

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! πŸ’―


Tags

#Javascript

Share

Previous Article
πŸ”₯ Mastering `Set` in JavaScript: The Underrated Power Tool for Unique Data

Table Of Contents

1
πŸ”Ή Spread Operator (...)
2
πŸ”Έ Rest Operator (...)

Related Posts

How `this` behaves in JavaScript
April 24, 2025
1 min
Β© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media