Destructuring - Exercise 1

Destructuring is a JavaScript syntax that lets you unpack values from arrays or properties from objects into separate variables. It provides a cleaner and more readable way to extract data from complex structures.

javascript

// Without destructuring
const colors = ['red', 'green', 'blue'];
const first = colors[0];
const second = colors[1];

// With destructuring
const [firstColor, secondColor] = colors;
console.log(firstColor); // "red"
console.log(secondColor); // "green"

Array destructuring uses square brackets on the left side of an assignment. The variables are assigned values based on their position in the array.

javascript

const numbers = [10, 20, 30, 40];

// Destructure first three values
const [a, b, c] = numbers;

console.log(a); // 10
console.log(b); // 20
console.log(c); // 30

// You can destructure fewer values than the array has
const [first, second] = numbers;
console.log(first); // 10
console.log(second); // 20

You can skip elements in array destructuring by leaving empty spaces (commas) where you want to skip. This lets you grab only the values you need from specific positions.

javascript

const fruits = ['apple', 'banana', 'cherry', 'date'];

// Skip the second element
const [first, , third] = fruits;
console.log(first); // "apple"
console.log(third); // "cherry"

// Skip multiple elements
const [, , , fourth] = fruits;
console.log(fourth); // "date"

// Get first and last
const [head, , , tail] = fruits;
console.log(head); // "apple"
console.log(tail); // "date"

Object destructuring uses curly braces on the left side of an assignment. The variable names must match the property names in the object.

javascript

const person = {
  name: 'Alice',
  age: 25,
  city: 'New York'
};

// Destructure specific properties
const { name, age } = person;

console.log(name); // "Alice"
console.log(age); // 25

// Order does not matter in object destructuring
const { city, name: userName } = person;
console.log(city); // "New York"

You can assign a property to a variable with a different name using the syntax propertyName: newVariableName. This is useful when property names conflict with existing variables.

javascript

const product = {
  name: 'Laptop',
  price: 999,
  brand: 'TechCo'
};

// Rename properties during destructuring
const { name: productName, price: cost } = product;

console.log(productName); // "Laptop"
console.log(cost); // 999

// Original property names are not created as variables
// console.log(name); // Would cause an error
// console.log(price); // Would cause an error

Default values are used when the array element is undefined. You assign defaults using the = operator after the variable name.

javascript

const colors = ['red'];

// Set default values
const [primary, secondary = 'blue', tertiary = 'green'] = colors;

console.log(primary); // "red" (from array)
console.log(secondary); // "blue" (default value)
console.log(tertiary); // "green" (default value)

// Default is only used when value is undefined
const [a = 10, b = 20] = [5, undefined];
console.log(a); // 5 (from array)
console.log(b); // 20 (default value)

Default values in object destructuring work the same way as arrays. The default is used when the property is undefined or does not exist.

javascript

const settings = {
  theme: 'dark',
  fontSize: 16
};

// Set default values for missing properties
const { theme, fontSize, language = 'en' } = settings;

console.log(theme); // "dark"
console.log(fontSize); // 16
console.log(language); // "en" (default value)

// Combine renaming with default values
const { theme: colorTheme = 'light', volume = 50 } = settings;
console.log(colorTheme); // "dark"
console.log(volume); // 50 (default value)

You can destructure nested arrays by mirroring the structure on the left side of the assignment. Use nested square brackets to access inner arrays.

javascript

const matrix = [
  [1, 2],
  [3, 4],
  [5, 6]
];

// Destructure nested arrays
const [[a, b], [c, d]] = matrix;

console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4

// Skip inner elements
const [[first], , [, last]] = matrix;
console.log(first); // 1
console.log(last); // 6

Nested object destructuring uses curly braces within curly braces to access properties of inner objects. The pattern mirrors the object structure.

javascript

const user = {
  name: 'John',
  address: {
    city: 'Boston',
    country: 'USA'
  }
};

// Destructure nested object
const { name, address: { city, country } } = user;

console.log(name); // "John"
console.log(city); // "Boston"
console.log(country); // "USA"

// Note: address itself is not defined as a variable
// console.log(address); // Would cause an error

Destructuring provides an elegant way to swap variables without needing a temporary variable. You create an array on the right and destructure it on the left in reverse order.

javascript

let a = 1;
let b = 2;

console.log('Before:', a, b); // Before: 1 2

// Swap using destructuring
[a, b] = [b, a];

console.log('After:', a, b); // After: 2 1

// Swap multiple variables
let x = 'first';
let y = 'second';
let z = 'third';

[x, y, z] = [z, x, y];
console.log(x, y, z); // "third" "first" "second"

You can destructure parameters directly in the function signature. This is useful when a function receives an object or array and you only need specific values.

javascript

// Object destructuring in parameters
function greet({ name, age }) {
  console.log(`Hello, ${name}! You are ${age} years old.`);
}

greet({ name: 'Alice', age: 25 });
// Output: Hello, Alice! You are 25 years old.

// Array destructuring in parameters
function getSum([a, b, c]) {
  return a + b + c;
}

console.log(getSum([10, 20, 30])); // 60

// With default values
function createUser({ name = 'Guest', role = 'user' } = {}) {
  console.log(`${name} is a ${role}`);
}

createUser({ name: 'Bob' }); // Bob is a user
createUser(); // Guest is a user

The rest pattern uses three dots (...) to collect remaining elements into a new array. It must be the last element in the destructuring pattern.

javascript

const numbers = [1, 2, 3, 4, 5, 6];

// Get first element and rest
const [first, ...rest] = numbers;

console.log(first); // 1
console.log(rest); // [2, 3, 4, 5, 6]

// Get first two and rest
const [a, b, ...others] = numbers;

console.log(a); // 1
console.log(b); // 2
console.log(others); // [3, 4, 5, 6]

// Useful for separating head from tail
const [head, ...tail] = ['apple', 'banana', 'cherry'];
console.log(head); // "apple"
console.log(tail); // ["banana", "cherry"]