destructuring javascript array code example

Example 1: javascript object destructuring

//simple example with object------------------------------
let obj = {name: 'Max', age: 22, address: 'Delhi'};
const {name, age} = obj;

console.log(name);
//expected output: "Max"

console.log(age);
//expected output: 22

console.log(address);
//expected output: Uncaught ReferenceError: address is not defined

// simple example with array-------------------------------
let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]

Example 2: destructure array javascript

var [first, second, ...rest] = ["Mercury", "Earth", ...planets, "Saturn"];

Example 3: destructuring assignment

Destructuring assignment is special syntax introduced in ES6, 
for neatly assigning values taken directly from an object.

const user = { name: 'John Doe', age: 34 };

const { name, age } = user;
// name = 'John Doe', age = 34

Example 4: js object destructuring

const { [propName]: identifier } = expression;

Example 5: destructuring Object in JavaScript

let {name, country, job} = {name: "Sarah", country: "Nigeria", job: "Developer"};

console.log(name);//"Sarah"
console.log(country);//"Nigeria"
console.log(job);//Developer"

Example 6: js destructuring explained

const { identifier } = expression;

Tags:

Misc Example