JavaScript Destructuring
Written By: Avinash Malhotra
Updated on
Destructuring assignment
JavaScript Destructuring assignment in ES6 is an JS expression which allow us to get Arrays value or Object Properties in variables. The left-hand side of assignment will receive data from the Array or Object on right-hand side.
We use Destructuring for Array and Objects Data Structures.
Destructuring Example
let [x,y]=[2,3];
// x=2; y=3;
let {name, id}={ name:"abc", id:212 };
// name="abc"; id:212;
Array Destructuring
Array Destructuring can be used to declare variables and assign values using Array on left-hand with variable names as array elements, and values in another array on right-hand side. If value is not defined, the default value will be undefined
.
Array Destructuring Example
let [x,y,z]=[3,4,5];
// x=3
// y=4
// z=5
Variables declaration using destructuring
var [x]=[10];
let [x]=[10];
const [x]=[10];
Variables assignment using destructuring
[x]=[10];
Parameters using destructuring
function sayHi([x]){ return x};
sayHi(['avi']);
// x="avi"
Swapping variables using destructuring
We can easily swap two variables using one destructuring expression. There is no need to declare temporary variable for swapping now.
let [x,y]=[2,3];
// x=2; y=3;
[x,y]=[y,x];
// x=3; y=2;
Object Destructuring
Object Destructuring can be done by declaring variable in object key on left-hand side and assign value from another object on right-hand side.
let {name, id}={ name:"abc", id:212 };
// name="abc"; id:212;
Assignment without declaration
let x,y;
({x,y}={ x:2, y:3});
// x=2; y=3;
For Object assignment, var, let or const is required. If variable is already declared, used parenthesis (...) around assignment.
Default values
const {a= 2, b = 5} = {a: 10};
console.log(a); // 10
console.log(b); // 5