Destructuring, Spread & Rest
ES6-এর নীরবে বিপ্লবী syntax
1. Object Destructuring
obj-destruct.js
const user = { name: "Arif", age: 22, city: "Dhaka" };
// Basic — picks by property name
const { name, age } = user;
console.log(name, age);
// Rename
const { name: userName, city: userCity } = user;
console.log(userName, userCity);
// Default values when undefined
const { country = "Bangladesh" } = user;
console.log(country);
// Rest — collect remaining keys
const { name: n, ...rest } = user;
console.log(rest); // { age: 22, city: "Dhaka" }
Object destructuring মানে এক লাইনে multiple variable তৈরি —
const {a, b} = obj। Renaming, default value, rest — সবই সমর্থিত।2. Array Destructuring
arr-destruct.js
const [a, b, c] = [1, 2, 3];
console.log(a, b, c);
// Skip with empty slot
const [first, , third] = ["a", "b", "c"];
console.log(first, third);
// Default + rest
const [head = 0, ...tail] = [10, 20, 30, 40];
console.log(head, tail);
// Swap two values
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1
3. Nested Destructuring
nested.js
const response = {
status: 200,
data: {
user: { name: "Arif", address: { city: "Dhaka" } },
items: ["a", "b", "c"]
}
};
const {
data: {
user: { name, address: { city } },
items: [first, , third]
}
} = response;
console.log(name, city, first, third);
4. Function Parameter Destructuring
params.js
function greet({ name = "Friend", lang = "en" } = {}) {
const msgs = { en: "Hello", bn: "হ্যালো" };
return `${msgs[lang]}, ${name}!`;
}
console.log(greet()); // "Hello, Friend!"
console.log(greet({ name: "Arif", lang: "bn" })); // "হ্যালো, Arif!"
// Array params
const mid = ([a, , b]) => (a + b) / 2;
console.log(mid([10, 20, 30])); // 20
5. Spread in Calls and Literals
spread.js
// Spread in function call
const nums = [5, 3, 9, 1];
console.log(Math.max(...nums)); // 9
// Concatenate arrays
const a = [1, 2], b = [3, 4];
console.log([...a, ...b, 5]); // [1,2,3,4,5]
// Clone (shallow)
const arr = [...nums];
const obj = { ...{ x: 1, y: 2 } };
// Merge objects
const defaults = { theme: "light", lang: "en" };
const overrides = { lang: "bn" };
console.log({ ...defaults, ...overrides });
// Iterables to array
console.log([..."abc"]); // ["a","b","c"]
console.log([...new Set([1,2,2,3])]); // [1,2,3]
6. Rest in Function Parameters
rest.js
function log(level, ...messages) {
console.log(`[${level}]`, ...messages);
}
log("info", "started", "on port", 3000);
const sumAll = (...n) => n.reduce((a, b) => a + b, 0);
console.log(sumAll(1, 2, 3, 4)); // 10
Spread vs Rest — same syntax, opposite jobs
...x on the right of = or in a function call is spread (expand). ...x on the left or in a parameter list is rest (collect).
7. Glossary (শব্দকোষ)
| Term | Meaning | বাংলায় |
|---|---|---|
| Destructuring | Pattern that extracts values from arrays/objects into variables. | Array/object থেকে value বের করে variable-এ বসানোর pattern। |
| Renaming | { a: x } — pull a out under the name x. | { a: x } — a-কে x নামে নেওয়া। |
| Default value | { a = 5 } — used when the property is undefined. | Property undefined হলে fallback value। |
| Spread | ...x on the right — expands an iterable/object. | ডান পাশে ...x — iterable/object expand করে। |
| Rest | ...x on the left or in params — collects remaining values. | বাম পাশে বা parameter-এ ...x — বাকি value collect করে। |
| Shallow copy | Top-level copy; nested references are still shared. | উপরের level copy হয়, ভেতরের object-গুলো একই থাকে। |
| Swap | [x, y] = [y, x] — exchange two values in one line. | এক line-এ দুই variable অদলবদল। |
| Param destructuring | Destructure directly in a function's parameter list. | Function parameter-এই destructure করা। |
সংক্ষেপে: Destructuring এক line-এ multiple variable তৈরি করে — renaming, default, nested ও rest সবই সমর্থিত। Spread (
...x) ডান পাশে expand করে; rest (...x) বাম পাশে বা parameter-এ collect করে। Same syntax, opposite directions। Spread সবসময় shallow — nested object গুলো একই reference share করে।
8. Practice Problems
- Destructure
nameandagefrom a user object.✨ Show Answer
a1.jsconst { name, age } = { name: "Arif", age: 22, city: "Dhaka" }; console.log(name, age); - Rename
nametofullNamewhile destructuring.✨ Show Answer
a2.jsconst { name: fullName } = { name: "Arif Hossain" }; console.log(fullName); - Provide a default
role = "guest".✨ Show Answer
a3.jsconst { role = "guest" } = { name: "x" }; console.log(role); - Swap
xandyin one line.✨ Show Answer
a4.jslet x = 1, y = 2; [x, y] = [y, x]; console.log(x, y); - Get the head and tail of an array.
✨ Show Answer
a5.jsconst [head, ...tail] = [1, 2, 3, 4]; console.log(head, tail); - Use
...restto gather remaining object keys.✨ Show Answer
a6.jsconst { id, ...rest } = { id: 1, name: "a", age: 22 }; console.log(rest); - Concatenate two arrays with spread.
✨ Show Answer
a7.jsconsole.log([...[1,2], ...[3,4]]); - Override one field while preserving the rest.
✨ Show Answer
a8.jsconst u = { name: "Arif", age: 22, city: "Dhaka" }; console.log({ ...u, age: 23 }); - Pass array elements as arguments to
Math.max.✨ Show Answer
a9.jsconst arr = [3, 9, 1, 7]; console.log(Math.max(...arr)); - Build a function with rest
...argsthat returns the count and sum.✨ Show Answer
a10.jsconst stats = (...n) => ({ count: n.length, sum: n.reduce((a,b) => a+b, 0) }); console.log(stats(1, 2, 3, 4)); - Destructure response.data.user.name from a deeply nested object.
✨ Show Answer
a11.jsconst resp = { data: { user: { name: "Arif" } } }; const { data: { user: { name } } } = resp; console.log(name); - Build a
connect({ host, port = 80 })function.✨ Show Answer
a12.jsconst connect = ({ host, port = 80 }) => console.log(`${host}:${port}`); connect({ host: "localhost" }); connect({ host: "abcl.tech", port: 443 }); - Combine three arrays into one with spread.
✨ Show Answer
a13.jsconst all = [...[1,2], ...[3,4], ...[5]]; console.log(all); - Convert a string to an array of code-points.
✨ Show Answer
a14.jsconsole.log([..."হ্যালো"]); - Why is spread with
{...obj}shallow?✨ Show Answer
Answer: Spread copies enumerable own properties at the top level only — nested objects remain shared references. To deep-clone use
structuredClone(obj)in modern environments. - Use destructuring inside a forEach to print "key: value" lines from an object.
✨ Show Answer
a16.jsconst u = { name: "Arif", age: 22, city: "Dhaka" }; Object.entries(u).forEach(([k, v]) => console.log(`${k}: ${v}`));
Summary — Module 15
Destructuring extracts properties or array elements into named variables in one line. Default values, renames, nesting, and rest patterns all chain together. Spread expands an iterable into individual values; rest collects the remaining ones. Same syntax — opposite directions — depending on context.
Destructuring এক লাইনে অনেক variable; spread expand করে; rest collect করে। তিনটি tool আধুনিক JS-এ সর্বত্র।