// In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N, only the first N variables are assigned values. The values of the remaining variables will be undefined.
const foo = ['one', 'two'];
const [red, yellow, green, blue] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // undefined
console.log(blue); //undefined
You can use "defaults" in destructuring as well:
(function test({a = "foo", b = "bar"} = {}) {
console.log(a + " " + b);
})();
This is not restricted to function parameters,
but works in every destructuring expression.
// destructuring assignment when passing
// an object of properties to a function
function example({userOptions: {query, all = true, sort} = {}, array}) {
console.log(query, all, sort) // something false ascending
}
// for clarity, the above example is destructured the same as this
function example({userOptions, array}){
const {query, all = true, sort} = userOptions || {}
}
const userOptions = {query: 'something', all: false, sort: 'ascending'}
const array = []
example({userOptions, array})
/*
Array Destructuring: The following example shows us how to convert all
the elements of an array to a variable.
Object Destructuring: The following example shows us how to convert all
the properties of an object into a variable.
*/
//Array Destructuring
const friends = ['Bill', 'Gates'];
const [firstName, secondName] = friends;
console.log(secondName); //Gates
//Object Destructuring
const person = {name: "Bill Gates", age: 17, phone: "123456789"};
const {name} = person;
console.log(name); //Bill Gates
function printFirstAndSecondElement([first, second]) {
console.log('First element is ' + first + ', second is ' + second)
}
function printSecondAndFourthElement([, second, , fourth]) {
console.log('Second element is ' + second + ', fourth is ' + fourth)
}
var array = [1, 2, 3, 4, 5]
printFirstAndSecondElement(array)
printSecondAndFourthElement(array)
// before you would do something like this
const person = {
name: 'Sara',
age: 25,
gender: 'female'
}
let name = person.name;
let age = person.age;
let gender = person.gender;
console.log(name); // Sara
console.log(age); // 25
console.log(gender); // female
// assigning object attributes to variables
const person = {
name: 'Sara',
age: 25,
gender: 'female'
}
let name = person.name;
let age = person.age;
let gender = person.gender;
console.log(name); // Sara
console.log(age); // 25
console.log(gender); // female