Learn the basics to use the destructuring syntax to work with arrays and objects in JavaScript
The destructuring assignment syntax is a expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
So, having an object, we can use the destructuring syntax to extract just some values and put them into named variables:
const getAge = birthDate =>
Math.floor((new Date() - new Date(birthDate).getTime()) / (365.25 * 24 * 60 * 60 * 1000))
const person = {
firstName: 'Will',
lastName: 'Smith',
actor: true,
age: getAge('1968-09-25'),
}
const { firstName: name, age } = person;
console.log(name, age);
// expected output: 'Will', 50
// the age depends on when this code is executed
name
and age
contain the desired values.
The syntax also works on arrays:
const a = [1, 2, 3, 4, 5];
const [first, second] = a;
console.log(first, second);
// expected output: 1, 2
This statement creates 3 new variables by getting the items with index 0, 1, 4 from the array a
:
const a = [1, 2, 3, 4, 5];
const [first, second, , , fifth] = a;
console.log(first, second, fifth);
// expected output: 1, 2, 5