Skip to main content

Command Palette

Search for a command to run...

Destructuring in JavaScript

Updated
•2 min read•View as Markdown
Destructuring in JavaScript

What destructuring means

The destructuring syntax is a JavaScript syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Destructuring arrays

const marks = [55,45,30];
const [english, hindi, punjabi] = marks;
console.log(english)

Destructuring objects

const user = {
    name : 'Kartik Kumar',
    age : 25,
    intro(){
        console.log('My name is ', this.name)
    }
}

const {name, age, intro} = user;

intro();

alias name

const user = {
    name : 'Kartik Kumar',
    age : 25,
    intro(){
        console.log('My name is ', this.name)
    }
}

const {name : naam, age : umar, intro} = user;

intro();

Default values

const marks = [55,45,30];
const [english, hindi, punjabi, drawing = 0] = marks;
console.log(english);


const user = {
    name : 'Kartik Kumar',
    age : 25,
    intro(){
        console.log('My name is ', this.name)
    }
}

const {name, age, intro} = user;

intro();

Benefits of destructuring

  • Less Code

  • More readable

  • Function parameters become cleaner

Without destructuring

const user = {
  name: "Kartik",
  age: 21
};

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

With destructuring

const user = {
  name: "Kartik",
  age: 21
};

const { name, age } = user;