Destructuring, Spread & Rest

ES6-এর নীরবে বিপ্লবী syntax

~30 min Intermediate 16 practice problems Live runner

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 (শব্দকোষ)

TermMeaningবাংলায়
DestructuringPattern 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 copyTop-level copy; nested references are still shared.উপরের level copy হয়, ভেতরের object-গুলো একই থাকে।
Swap[x, y] = [y, x] — exchange two values in one line.এক line-এ দুই variable অদলবদল।
Param destructuringDestructure 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

  1. Destructure name and age from a user object.
    ✨ Show Answer
    a1.js
    const { name, age } = { name: "Arif", age: 22, city: "Dhaka" };
    console.log(name, age);
  2. Rename name to fullName while destructuring.
    ✨ Show Answer
    a2.js
    const { name: fullName } = { name: "Arif Hossain" };
    console.log(fullName);
  3. Provide a default role = "guest".
    ✨ Show Answer
    a3.js
    const { role = "guest" } = { name: "x" };
    console.log(role);
  4. Swap x and y in one line.
    ✨ Show Answer
    a4.js
    let x = 1, y = 2;
    [x, y] = [y, x];
    console.log(x, y);
  5. Get the head and tail of an array.
    ✨ Show Answer
    a5.js
    const [head, ...tail] = [1, 2, 3, 4];
    console.log(head, tail);
  6. Use ...rest to gather remaining object keys.
    ✨ Show Answer
    a6.js
    const { id, ...rest } = { id: 1, name: "a", age: 22 };
    console.log(rest);
  7. Concatenate two arrays with spread.
    ✨ Show Answer
    a7.js
    console.log([...[1,2], ...[3,4]]);
  8. Override one field while preserving the rest.
    ✨ Show Answer
    a8.js
    const u = { name: "Arif", age: 22, city: "Dhaka" };
    console.log({ ...u, age: 23 });
  9. Pass array elements as arguments to Math.max.
    ✨ Show Answer
    a9.js
    const arr = [3, 9, 1, 7];
    console.log(Math.max(...arr));
  10. Build a function with rest ...args that returns the count and sum.
    ✨ Show Answer
    a10.js
    const stats = (...n) => ({ count: n.length, sum: n.reduce((a,b) => a+b, 0) });
    console.log(stats(1, 2, 3, 4));
  11. Destructure response.data.user.name from a deeply nested object.
    ✨ Show Answer
    a11.js
    const resp = { data: { user: { name: "Arif" } } };
    const { data: { user: { name } } } = resp;
    console.log(name);
  12. Build a connect({ host, port = 80 }) function.
    ✨ Show Answer
    a12.js
    const connect = ({ host, port = 80 }) => console.log(`${host}:${port}`);
    connect({ host: "localhost" });
    connect({ host: "abcl.tech", port: 443 });
  13. Combine three arrays into one with spread.
    ✨ Show Answer
    a13.js
    const all = [...[1,2], ...[3,4], ...[5]];
    console.log(all);
  14. Convert a string to an array of code-points.
    ✨ Show Answer
    a14.js
    console.log([..."হ্যালো"]);
  15. 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.

  16. Use destructuring inside a forEach to print "key: value" lines from an object.
    ✨ Show Answer
    a16.js
    const 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-এ সর্বত্র।

Next Module → Prototypes & The Prototype Chain।