Lab 01: ES6 Destructuring & Spread

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Master modern JavaScript syntax: destructuring assignments, rest/spread operators, computed property names, and shorthand methods. These features make code cleaner and more expressive.


Step 1: Array Destructuring

// Basic array destructuring
const [first, second, third] = [10, 20, 30];
console.log(first, second, third); // 10 20 30

// Skipping elements
const [, , last] = [1, 2, 3];
console.log(last); // 3

// Default values
const [a = 0, b = 0, c = 0] = [1, 2];
console.log(a, b, c); // 1 2 0

// Swapping variables
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1

💡 Destructuring doesn't mutate the original array. It creates new bindings.


Step 2: Object Destructuring

💡 Object destructuring uses property names as keys; order doesn't matter unlike arrays.


Step 3: Nested Destructuring


Step 4: Rest Parameters

💡 Rest must always be the last element. const [...rest, last] is a syntax error.


Step 5: Spread Operator


Step 6: Computed Property Names


Step 7: Shorthand Methods & Property Shorthand


Step 8: Capstone — Config Parser

Build a configuration parser that uses all concepts from this lab:

Run it:

📸 Verified Output:


Summary

Feature
Syntax
Use Case

Array destructuring

const [a, b] = arr

Unpack arrays, swap vars

Object destructuring

const {x, y} = obj

Unpack objects, function params

Nested destructuring

const {a: {b}} = obj

Deep data extraction

Rest (array)

const [first, ...rest] = arr

Collect remaining elements

Rest (object)

const {a, ...rest} = obj

Omit specific properties

Rest (params)

function f(...args)

Variadic functions

Spread (array)

[...arr1, ...arr2]

Merge/copy arrays

Spread (object)

{...obj1, ...obj2}

Merge/copy objects

Computed props

{[expr]: value}

Dynamic property names

Shorthand

{name, method() {}}

Concise object literals

Last updated