Destructuring in JavaScript(beginner to advance)

Published: (March 26, 2026 at 05:36 AM EDT)
3 min read
Source: Dev.to

Source: Dev.to

Without Destructuring

const user = {
  name: "John",
  age: 20,
  city: "Mumbai"
};

const name = user.name;
const age = user.age;
const city = user.city;

console.log(name, age, city);

With Destructuring

const user = {
  name: "John",
  age: 20,
  city: "Mumbai"
};

const { name, age, city } = user;

console.log(name, age, city);

Object Destructuring

Basic Assignment

const user = { name: 'Alice', age: 25 };
const { name, age } = user; // name = 'Alice', age = 25

Renaming

const user = { name: 'Alice' };
const { name: userName } = user; // userName = 'Alice'

Default Values

const user = {};
const { city = 'Unknown' } = user; // city = 'Unknown'

Nested Destructuring

const profile = { id: 1, info: { email: 'a@ex.com' } };
const { info: { email } } = profile; // email = 'a@ex.com'

Array Destructuring

Basic Assignment

const colors = ['red', 'blue', 'green'];
const [first, second] = colors; // first = 'red', second = 'blue'

Skipping Values

const colors = ['red', 'blue', 'green'];
const [first, , third] = colors; // first = 'red', third = 'green'

Swapping Variables

let a = 4;
let b = 5;

[a, b] = [b, a]; // a = 5, b = 4

How it works

  1. The right‑hand side array [b, a] is evaluated first, producing [5, 4].
  2. The destructuring on the left side [a, b] = [5, 4] then assigns a = 5 and b = 4.

Rest Operator

const numbers = [1, 2, 3, 4];
const [one, ...others] = numbers; // one = 1, others = [2, 3, 4]

Important Points of Destructuring

  • Destructuring does not modify the original object or array; it only extracts values.
  • It creates a shallow copy. Nested objects or arrays remain references to the original data.
const user = {
  name: "Abhi",
  address: {
    city: "Jalandhar"
  }
};

const { address } = user;
address.city = "Delhi";

console.log(user.address.city); // Delhi (original also changed)
  • Attempting to destructure null or undefined throws a TypeError.
const { name } = null; // TypeError

Conclusion

Destructuring in JavaScript (introduced in ES6) provides a concise syntax for extracting values from objects and arrays, improving readability and reducing boilerplate code. It supports renaming, default values, nested structures, the rest operator, and even enables elegant variable swapping without temporary placeholders.

0 views
Back to Blog

Related posts

Read more »

what is looping in j.s

Looping in JavaScript Looping in JavaScript is useful when you want to perform the same task again and again without writing the same code repeatedly. Types of...

NetNostalgia

Overview I’ve always been fascinated by how fast the internet evolved. From messy, colorful websites in the 90s to the clean, minimal design we have today — it...