Today was a deviation from freecodecamp challenges as I have started learning JavaScript ES6. I learned about destructuring arrays and objects in JavaScript .
Destructuring in JavaScript is a JavaScript expression for unpacking values from an array and properties from objects, then assigning them to a variable.
Examples
- Basic Array Destructuring
var [a,b] = [1,2];
console.log(a); // prints 1
console.log(b); // prints 2
Explanation
The code above basically takes(unpacks) the first value 1 on the right hand and assign it to variable a and takes(unpacks) the second value 2 and assign it to variable b too.
- Basic Objects Destructuring
var {a,b} = {a:2, b:5};
console.log(a) //prints 2
console.log(b) //prints 5
Explanation
We declare an object on the right hand side. Checked if properties a and b are present on both sides, get their values and assigned them to the same variables a and b respectively;