![]() |
VOOZH | about |
Destructuring assignment in JavaScript allows us to unpack the values from arrays or objects and assign them to multiple variables.
Syntax
// Destructuring from Array, arr = [ 10, 15 ]
let [ a, b ] = arr; // a=> 10, b => 15
// Destructuring from Array, obj = { n1: 10, n2: 15 ]
let [ n1, n2 ] = obj;
JavaScript destructing assignment is used to swap the elements by swapping the variable positions in the destructuring array.
Syntax
// Swaping the values of a and b
[ a, b] = [ b, a ]
Example: This example uses the JavaScript destructuring assignment to swap the values of two variables.
Updated Values= a: 25 b: 10
Example 2: This example swaps the values of 3 variables using destructuring assignment in JavaScript.
Updated Values= a: 40 b: 50 c: 30