JavaScript Destructuring
Written By: Avinash Malhotra
Updated on
Destructuring assignment
JavaScript Destructuring assignment in ES6 is a JavaScript expression that allows us to unpack array values or object properties into variables. The left-hand side of the assignment receives data from the array or object on the right-hand side.
We use destructuring for arrays 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 an array on the left-hand side with variable names as array elements, and values from another array on the right-hand side. If a value is not provided, it defaults to 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 variables with object keys on the left-hand side and assigning values from another object on the 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 the variable is already declared, use parentheses (...) around the assignment.
Default values
const {a= 2, b = 5} = {a: 10};
console.log(a); // 10
console.log(b); // 5
Summary
JavaScript destructuring, introduced in ES6, allows unpacking values from arrays or properties from objects into distinct variables. It simplifies variable assignment, supports default values, and enables easy swapping of variables, making code more readable and concise.