JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Destructuring


JavaScript destructuring is a syntax that allows you to extract values from arrays or objects into separate variables. Introduced in ES6, it simplifies code that previously required multiple lines to access array elements or object properties. Destructuring improves readability, reduces boilerplate code, and makes it easier to work with complex data structures.

Destructuring is widely used in function arguments, API responses, React props, and array manipulation. Understanding it deeply will make your JavaScript code cleaner and more maintainable.

What is Destructuring Array?

Array destructuring allows you to assign elements of an array to variables in a single line.

// Traditional way of extracting array elements
const numbers = [1, 2, 3];
const a = numbers[0];
const b = numbers[1];
const c = numbers[2];

console.log(a, b, c); // Logs: 1 2 3

With array destructuring, this becomes simpler:

const numbers = [1, 2, 3];

// Destructuring assignment
const [first, second, third] = numbers;

console.log(first, second, third); // Logs: 1 2 3
  • The variables first, second, third correspond to array elements in order.

  • You can skip elements using commas:

const [,, thirdValue] = numbers;
console.log(thirdValue); // Logs: 3
  • You can also use default values if an element is undefined:

const [x = 10, y = 20, z = 30] = [1];
console.log(x, y, z); // Logs: 1 20 30

What is Destructuring Object?

Object destructuring allows you to extract properties from an object into variables.

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

// Destructuring
const { name, age, city } = person;

console.log(name, age, city); // Logs: Alice 25 New York
  • Variable names must match property names unless you use aliasing:

const { name: fullName, age: years } = person;
console.log(fullName, years); // Logs: Alice 25
  • Default values can also be used for missing properties:

const { country = "USA" } = person;
console.log(country); // Logs: USA

Nested Destructuring

Destructuring works with nested objects and arrays as well.

const user = {
  id: 1,
  profile: {
    username: "alice123",
    email: "alice@example.com"
  }
};

// Nested object destructuring
const { profile: { username, email } } = user;

console.log(username, email); // Logs: alice123 alice@example.com

Array within objects or nested arrays can also be destructured:

const data = [1, [2, 3], 4];
const [a, [b, c], d] = data;
console.log(a, b, c, d); // Logs: 1 2 3 4

Destructuring in Function Parameters

Destructuring is commonly used in function arguments for cleaner code.

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

const person1 = { name: "Bob", age: 30 };
greet(person1); // Logs: Hello Bob, you are 30 years old

Array destructuring in function parameters:

function sum([a, b]) {
  return a + b;
}

console.log(sum([5, 10])); // Logs: 15

This avoids creating extra variables inside the function body.

Swapping Variables

Destructuring provides a concise way to swap values without using a temporary variable:

let x = 10;
let y = 20;

// Swap values using array destructuring
[x, y] = [y, x];

console.log(x, y); // Logs: 20 10

Rest Syntax with Destructuring

You can use the rest operator (...) to collect remaining elements in arrays or properties in objects.

// Array rest
const arr = [1, 2, 3, 4, 5];
const [first, second, ...rest] = arr;
console.log(first, second, rest); // Logs: 1 2 [3, 4, 5]

// Object rest
const user2 = { name: "Alice", age: 25, city: "NY" };
const { name, ...other } = user2;
console.log(name, other); // Logs: Alice { age: 25, city: "NY" }

Combining Destructuring with Default Values and Aliasing

const product = {
  id: 101,
  title: "Laptop",
  price: 1500
};

// Destructuring with alias and default
const { title: productName, price: cost, discount = 0 } = product;

console.log(productName, cost, discount); // Logs: Laptop 1500 0
  • This is extremely useful when working with APIs where some fields may be optional.

Advanced Use Cases

  • Nested defaults:

const user3 = { profile: { name: "Charlie" } };
const { profile: { name, age = 18 } } = user3;
console.log(name, age); // Logs: Charlie 18
  • Destructuring return values from functions:

function getCoordinates() {
  return [10, 20];
}

const [xCoord, yCoord] = getCoordinates();
console.log(xCoord, yCoord); // Logs: 10 20
  • Skipping unnecessary elements:

const rgb = [255, 200, 150];
const [, , blue] = rgb;
console.log(blue); // Logs: 150

Summary of the Tutorial

  • Array destructuring allows extracting elements in order into variables.

  • Object destructuring extracts properties by name, with optional aliasing and default values.

  • Supports nested destructuring, rest syntax, and function parameter destructuring.

  • Makes code cleaner, readable, and maintainable, especially with API responses or complex data structures.

  • Reduces the need for repetitive code and temporary variables.

Destructuring is an essential ES6 feature that every JavaScript developer should master, as it is used heavily in modern JavaScript frameworks and libraries.


Practice Questions

  1. Destructure the array [10, 20, 30] into three separate variables and log them.

  2. Destructure the object { name: "Alice", age: 25, city: "NY" } into variables name, age, and city and log them.

  3. Use destructuring to swap the values of two variables x = 5 and y = 10 without using a temporary variable.

  4. Destructure the nested object { user: { id: 1, username: "bob" } } to extract id and username.

  5. Use array destructuring with the rest operator to extract the first two elements of [1, 2, 3, 4, 5] and store the remaining elements in another array.

  6. Destructure an object { title: "Book", price: 100 } with a default value for discount = 0 and log all three variables.

  7. Write a function that takes an object { name, age } as a parameter and uses destructuring in the function signature to log a greeting message.

  8. Destructure the array [5, 10, 15] but skip the second element and log only the first and third elements.

  9. Use nested destructuring to extract values from [1, [2, 3], 4] into separate variables and log them.

  10. Destructure the return value of a function that returns [x, y] = [100, 200] and log both variables.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top