30 Days Of JavaScript.11
Day 11. Destructuring and Spreading
On
Day 11
, I learned about destructuring and spreading. I can easily assign new variables with these methods.
Destructuring and Spread
Destructuring is a way to unpack values from arrays, or properties from objects, into distinct variables.
1. Destructing Arrays
const numbers = [1, 2, 3];
let [num1, num2, num3] = numbers;
console.log(num1, num2, num3); // 1 2 3
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
];
const [frontEnd, backEnd] = fullStack;
console.log(frontEnd); // ['HTML', 'CSS', 'JS', 'React']
console.log(backEnd); // ['Node', 'Express', 'MongoDB']
If I want to skip(ignore) one of the values in the array, I can use additional comma. The comma helps to omit the value at that specific index.
const names = ['Luther', 'Diego', 'Klaus', 'Ben'];
let [, secondPerson, , fourthPerson] = names;
// first and third person is omitted
console.log(secondPerson, fourthPerson);
// Diego Ben
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 nums = [1, 2, 3];
// a, b, c, d are all variables, so using '' will give a syntax error
const [a, b, c, d] = nums;
console.log(c); // 3
console.log(d); // undefined
I can use a default value, in case that the value of array for that index is undefined
.
const names = ['Allison', undefined, 'Vanya'];
let [
firstPerson,
secondPerson = 'Five',
thirdPerson,
fourthPerson = 'Pogo'
] = names;
console.log(firstPerson, secondPerson, thirdPerson, fourthPerson);
// Allison Five Vanya Pogo
I cannot assign variable to all the elements in the array. I can destructure few ot the first elements, and then get the remaining values as an array, using a spread operator(...
).
const nums = [1, 2, 3, 4, 5, 6, 7];
let [num1, num2, num3, ...rest] = nums;
console.log(num1, num2, num3); // 1, 2, 3
console.log(rest); // [4, 5, 6, 7]
2. Destructuring during iteration
const countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo']
];
for (const [country, city] of countries) {
console.log(country, city);
}
/*
Finland Helsinki
Sweden Stockholm
Norway Oslo
*/
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
];
for (const [first, second, third] of fullStack) {
console.log(first, second, third);
}
// HTML CSS JS
// Node Express MongoDB
3. Destructuring Object
When I destructure the name of the variable, the variable I use to destructure should be exactly the same as the key or property of the object.
const rectangle = {
width: 20,
height: 10,
area: 200
}
let {width, height, area, perimeter} = rectangle;
console.log(width, height, area, perimeter);
// 20 10 200 undefined
4. Renaming during structuring
const rectangle = {
width: 20,
height: 10,
area: 200
}
let {width: w, height: h, area: a, perimeter: p} = rectangle;
console.log(w, h, a, p); // 20 10 200 undefined
console.log(width, height, area, perimeter);
// ReferenceError: width is not defined
If the key is not found in the object, the variable will be assigned to undefined
. In case the key is not in the object, I can give a default value during declaration(structuring).
const rectangle = {
width: 20,
height: 10,
area: 200
}
let {width, height, area, perimeter = 60} = rectangle;
console.log(width, height, area, perimeter);
// 20 10 200 60
If the key and its value are already defined at the object, the value doesn’t change even if I declare a new value during declaration.
const rectangle = {
width: 20,
height: 10,
area: 200,
perimeter: 80
}
let {width, height, area, perimeter = 60} = rectangle;
console.log(width, height, area, perimeter);
// 20 10 200 80
5. Object parameter without destructuring
I can desturcture arrays or objects by passing them as arguments.
I can destructure keys as a function parameters. Down below, a function takes a rectangle object and returns a perimeter of a rectangle.
//without destructuring
const rect = {
width: 20,
height: 10
}
const calculatePerimeter = rectangle => {
return 2 * (rectangle.width + rectangle.height);
}
console.log(calculatePerimeter(rect)); // 60
const person = {
firstName: 'Ramona',
lastName: 'Doe',
age: 23,
country: 'Korea',
job: 'student',
skills: ['HTML', 'CSS', 'JavaScript'],
languages: ['Korean', 'English', 'Spanish']
}
// create a function which gives information about the person object without destructuring
const getPersonInfo = obj => {
const skills = obj.skills;
const formattedSkills = skills.slice(0, -1).join(', ');
const languages = obj.languages;
const formattedLanguages = languages.slice(0, -1).join(', ');
let personInfo = `${obj.firstName} ${obj.lastName} lives in ${obj.country}. She is ${obj.age} years old. She is a ${obj.job}. She learns ${formattedSkills} and ${skills[skills.length - 1]}. She speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo;
}
console.log(getPersonInfo(person));
// Ramona Doe lives in Korea. She is 23 years old. She is a student. She learns HTML, CSS and JavaScript. She speaks Korean, English and a little bit of Spanish.
5. Object parameter with destructuring
// with destructing
const rect = {
width: 20,
height: 10
}
const calculatePerimeter = ({ width, height }) => {
return 2 * (width + height);
}
console.log(calculatePerimeter(rect)); // 60
const person = {
firstName: 'Ramona',
lastName: 'Doe',
age: 23,
country: 'Korea',
job: 'student',
skills: ['HTML', 'CSS', 'JavaScript'],
languages: ['Korean', 'English', 'Spanish']
}
// create a function which gives information about the person object with destructuring
const getPersonInfo = ({
firstName,
lastName,
age,
country,
job,
skills,
languages
}) => {
const formattedSkills = skills.slice(0, -1).join(', ');
const formattedLanguages = languages.slice(0, -1).join(', ');
let personInfo = `${firstName} ${lastName} lives in ${country}. She is ${age} years old. She is a ${job}. She learns ${formattedSkills} and ${skills[skills.length - 1]}. She speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo;
}
console.log(getPersonInfo(person));
// Ramona Doe lives in Korea. She is 23 years old. She is a student. She learns HTML, CSS and JavaScript. She speaks Korean, English and a little bit of Spanish.
Using destructuring allows me to access to object values without using dot notation or bracket notation, hence more efficient and readable.
6. Destructing object during iteration
const todoList = [
{
task : 'Prepare JS Test',
time: '4/1/2020 8:30',
completed: true
},
{
task: 'Give JS Test',
time: '4/1/2020 10:00',
completed: false
},
{
task: 'Assess Test Result',
time: '4/1/2020 1:00',
completed: false
}]
for (const {task, time, completed} of todoList) {
console.log(task, time, completed);
}
/*
Prepare JS Test 4/1/2020 8:30 true
Give JS Test 4/1/2020 10:00 false
Assess Test Result 4/1/2020 1:00 false
*/
7. Spread or Rest Operator
When destrcuturing an array, spread operator(...
) is used to get the rest elements as an array. In addition to that, spread operator(...
) is used to spread array elements to another array.
8. Spread operator to get the rest of array elements
const nums = [1, 2, 3, 4, 5, 6, 7];
let [num1, num2, num3, ...rest];
console.log(num1, num2, num3); // 1 2 3
console.log(rest); // [4, 5, 6, 7]
const countries = [
'Germany',
'France',
'Belgium',
'Finland',
'Sweden',
'Norway',
'Denmark',
'Iceland'
]
// notice the additional comma - it skips one element
let [gem, fra, , ...nordicCountries] = countries;
console.log(gem); // Germany
console.log(fra); // France
console.log(nordicCountries);
// ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
9. Spread operator to copy array
const evens = [0, 2, 4, 6, 8];
const evenNumbers = [...evens];
const odds = [1, 3, 5, 7, 9];
const oddNumbers = [...odds];
const wholeNumbers = [...evens, ...odds];
console.log(evenNumbers); // [0, 2, 4, 6, 8]
console.log(oddNumbers); // [1, 3, 5, 7, 9]
console.log(wholeNumbers);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const frontEnd = ['HTML', 'Css', 'JS', 'React'];
const backEnd = ['Node', 'Express', 'MongoDB'];
const fullStack = [...frontEnd, ...backEnd];
console.log(fullStack);
// ['HTML', 'Css', 'JS', 'React', 'Node', 'Express', 'MongoDB']
10. Spread operator to copy object
const user = {
name: 'Ramona',
title: 'Programmer',
country: 'Korea',
hasACat: false
}
const copiedUser = {...user};
console.log(copiedUser);
// {name: 'Ramona', title: 'Programmer', country: 'Korea', hasACat: false}
I can modify or change the object while copying.
const user = {
name: 'Ramona',
title: 'Programmer',
country: 'Korea',
hasACat: false
}
const copiedUser = {...user, title: 'Student'};
console.log(copiedUser);
// {name: 'Ramona', title: 'Student', country: 'Korea', hasACat: false}
11. Spread operator with arrow function
A spread operator(...
) can be used when I want to write an arrow function which takes unlimited number of arguments.
const sumAllNums = (...args) => {
console.log(args);
}
sumAllNums(1, 2, 3, 4, 5);
// [1, 2, 3, 4, 5]
const sumAllNums = (...args) => {
let sum = 0;
for (const num of args) {
sum += num
}
return sum;
}
console.log(sumAllNums(1, 3, 5, 7));
// 16
Leave a comment