D DevBrainBox

JavaScript Destructuring

JS

What is destructuring?

Destructuring is a feature in JavaScript (introduced in ES6) that lets you unpack values from arrays or properties from objects into distinct variables.

  • It makes your code shorter and cleaner.

Example 1: Array destructuring

javascript CopyEdit

const numbers = [10, 20, 30];

// without destructuring
const first = numbers[0];
const second = numbers[1];

// with destructuring
const [a, b, c] = numbers;

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

You can also skip elements:

const [x, , z] = numbers;
console.log(x); // 10
console.log(z); // 30

Example 2: Object destructuring

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

// without destructuring
const name1 = person.name;
const age1 = person.age;

// with destructuring
const { name, age, city } = person;

console.log(name); // Alice
console.log(age);  // 25
console.log(city); // New York

You can also give them new variable names:

const { name: fullName, age: years } = person;
console.log(fullName); // Alice
console.log(years);    // 25

Function parameters with destructuring

Very handy for functions:

function greet({ name, city }) {
 console.log(`Hello ${name} from ${city}!`);
}

greet(person); // Hello Alice from New York!
  • Destructuring lets you extract values from arrays or objects into individual variables in a quick, elegant way.

On this page