Skip to main content

Command Palette

Search for a command to run...

Destructuring in JavaScript

A simple guide to unpacking values from arrays and objects — with clear examples and visuals.

Updated
2 min readView as Markdown
Destructuring in JavaScript

What is Destructuring?

Imagine you have a gift box with many items inside. Instead of reaching into the box every time you need something, you take everything out and put it on the table neatly organized.

That is exactly what destructuring does in JavaScript. It lets you pull out values from arrays or objects and put them into separate variables — all in one clean step.

Destructuring = "unpack values into variables, quickly and neatly."


Destructuring Arrays

With arrays, destructuring assigns values based on their position. The first variable gets the first item, the second variable gets the second item, and so on.

The square brackets [ ] on the left side tell JavaScript: "I want to unpack this array."

You can also skip items using an empty comma:

const [, second] = ["apple", "banana", "mango"]; console.log(second); // "banana" ← skipped "apple"

Destructuring Objects

With objects, destructuring matches by property name, not position. The variable name must match the key in the object.

You can also give the variable a different name using a colon:

const { name: userName } = user; console.log(userName); // "omkar" ← renamed from 'name'

Default Values

What if a value doesn't exist in the array or object? Without a default value, you get undefined. With a default value, you get a safe fallback instead.

const [a = "hello", b = "world"] = ["hi"]; console.log(a); // "hi" ← value existed, used it console.log(b); // "world" ← no value, used default
const { name, role = "viewer" } = { name: "Rahul" }; console.log(name); // "Rahul" ← existed in object console.log(role); // "viewer" ← not in object, used default

Default values only kick in when the value is undefined. If the value is null, the default does NOT apply.


Benefits of Destructuring

Destructuring is not just shorter — it makes your code much easier to read and manage.