You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

698 lines
16 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

<div align="center">
<h1> 30 Days Of JavaScript</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
</div>
[<< Day 10](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/10_Day/10_day_Set_and_Map.md) | [Day 12>>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/12_Day/12_day_regular_expressions.md)
![Day 11](../images/banners/day_1_11.png)
- [Day 11](#day-11)
- [Destructuring and Spread](#destructuring-and-spread)
- [Destructing Arrays](#destructing-arrays)
- [Destructuring during iteration](#destructuring-during-iteration)
- [Destructuring Object](#destructuring-object)
- [Renaming during structuring](#renaming-during-structuring)
- [Object parameter without destructuring](#object-parameter-without-destructuring)
- [Object parameter with destructuring](#object-parameter-with-destructuring)
- [Destructuring object during iteration](#destructuring-object-during-iteration)
- [Spread or Rest Operator](#spread-or-rest-operator)
- [Spread operator to get the rest of array elements](#spread-operator-to-get-the-rest-of-array-elements)
- [Spread operator to copy array](#spread-operator-to-copy-array)
- [Spread operator to copy object](#spread-operator-to-copy-object)
- [Spread operator with arrow function](#spread-operator-with-arrow-function)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 11
## Destructuring and Spread
Destructuring is a way to unpack arrays, and objects and assigning to a distinct variable.
### Destructing Arrays
```js
const numbers = [1, 2, 3]
let [numOne, numTwo, numThree] = numbers
console.log(numOne, numTwo, numThree)
```
```sh
1 2 3
```
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
let [firstPerson, secondPerson, ThirdPerson, fourth Person] = names
console.log(firstName, secondPerson,thirdPerson, fourthPerson)
```
```sh
Asabeneh Brook David John
```
```js
const scientificConstants = [2.72, 3.14, 9.81, 37, 100]
let [e, pi, gravity, bodyTemp, boilingTemp] = scientificConstants
console.log(e,pi,gravity, bodyTemp, boilingTemp)
```
```sh
2.72 3.14 9.81 37 100
```
```js
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]
const [frontEnd, backEnd] = fullStack
console.log(frontEnd)
console.log(backEnd)
```
```sh
["HTML", "CSS", "JS", "React"]
["Node", "Express", "MongoDB"]
```
If we like to skip on of the values in the array we use additional comma. The comma helps to omit the value at that specific index
```js
const numbers = [1, 2, 3]
let [numOne, , numThree] = numbers //2 is omitted
console.log(numOne, numThree)
```
```sh
1 3
```
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
let [, secondPerson, , fourth Person] = name // first and third person is omitted
console.log(secondPerson, fourthPerson)
```
```sh
Brook John
```
We can use default value in case the value of array for that index is undefined:
```js
const names = [undefined, 'Brook', 'David']
let [
firstPerson = 'Asabeneh',
secondPerson,
thirdPerson,
fourthPerson = 'John'
] = names
console.log(firstPerson, secondPerson, thirdPerson, fourthPerson)
```
```sh
Asabeneh Brook David John
```
We can not assign variable to all the elements in the array. We can destructure few of the first and we can get the remaining as array using spread operator(...).
```js
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [num1, num2, num3, ...rest] = nums
console.log(num1, num2, num3)
console.log(rest)
```
```sh
1 2 3
[4, 5, 6, 7, 8, 9, 10]
```
### Destructuring during iteration
```js
const countries = [['Finland', 'Helsinki'], ['Sweden', 'Stockholm'], ['Norway', 'Oslo']]
for (const [country, city] of countries) {
console.log(country, city)
}
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
```
```js
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]
for(const [first, second, third] of fullStack) {
console.log(first, second, third)
}
```
```sh
HTML CSS JS
Node Express MongoDB
```
### Destructuring Object
When we destructure the name of the variable we use to destructure should be exactly the same as the key or property of the object. See the example below.
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width, height, area, perimeter } = rectangle
console.log(width, height, area, perimeter)
```
```sh
20 10 200 undefined
```
### Renaming during structuring
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width: w, heigh: h, area: a, perimeter: p } = rectangle
console.log(w, h, a, p)
```
```sh
20 10 200 undefined
```
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 we can give a default value during declaration. See the example.
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width, heigh, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //20 10 200 60
//Lets modify the object:width to 30 and perimeter to 80
```
```js
const rectangle = {
width: 30,
height: 10,
area: 200,
perimeter: 80
}
let { width, heigh, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //20 10 200 80
```
Destructuring keys as a function parameters. Lets create a function which take a rectangle object and it return a perimeter of a rectangle.
### Object parameter without destructuring
```js
// Without destructuring
const rect = {
width: 20,
height: 10
}
const calculatePerimeter = rectangle => {
return 2 * (rectangle.width + rectangle.height)
}
console.log(calculatePerimeter(rect)) // 60
//with destructuring
```
```js
//Another Example
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
job: 'Instructor and Developer',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB',
'Python',
'D3.js'
],
languages: ['Amharic', 'English', 'Suomi(Finnish)']
}
// Lets create a function which give 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(', ')
personInfo = `${obj.firstName} ${obj.lastName} lives in ${obj.country}. He is ${
obj.age
} years old. He is an ${obj.job}. He teaches ${formattedSkills} and ${
skills[skills.length - 1]
}. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo
}
console.log(getPersonInfo(person))
```
### Object parameter with destructuring
```js
const calculatePerimeter = ({ width, height }) => {
return 2 * (width + height)
}
console.log(calculatePerimeter(rect)) // 60
```
```js
// Lets create a function which give 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(', ')
personInfo = `${firstName} ${lastName} lives in ${country}. He is ${age} years old. He is an ${job}. He teaches ${formattedSkills} and ${
skills[skills.length - 1]
}. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo
}
console.log(getPersonInfo(person))
/*
Asabeneh Yetayeh lives in Finland. He is 200 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)
*/
```
### Destructuring object during iteration
```js
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)
}
```
```sh
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
```
### Spread or Rest Operator
When we destructure an array we use the spread operator(...) to get the rest elements as array. In addition to that we use spread operator to spread arr elements to another array.
### Spread operator to get the rest of array elements
```js
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [num1, num2, num3, ...rest] = nums
console.log(num1, num2, num3)
console.log(rest)
```
```sh
1 2 3
[4, 5, 6, 7, 8, 9, 10]
```
```js
const countries = [
'Germany',
'France',
'Belgium',
'Finland',
'Sweden',
'Norway',
'Denmark',
'Iceland'
]
let [gem, fra, , ...nordicCountries] = countries
console.log(gem)
console.log(fra)
console.log(nordicCountries)
```
```sh
Germany
France
["Finland", "Sweden", "Norway", "Denmark", "Iceland"]
```
### Spread operator to copy array
```js
const evens = [0, 2, 4, 6, 8, 10]
const evenNumbers = [...evens]
const odds = [1, 3, 5, 7, 9]
const oddNumbers = [...odds]
const wholeNumbers = [...evens, ...odds]
console.log(evenNumbers)
console.log(oddNumbers)
console.log(wholeNumbers)
```
```sh
[0, 2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
```
```js
const frontEnd = ['HTML', 'CSS', 'JS', 'React']
const backEnd = ['Node', 'Express', 'MongoDB']
const fullStack = [...frontEnd, ...backEnd]
console.log(fullStack)
```
```sh
["HTML", "CSS", "JS", "React", "Node", "Express", "MongoDB"]
```
### Spread operator to copy object
We can copy an object using a spread operator
```js
const user = {
name:'Asabeneh',
title:'Programmer',
country:'Finland',
city:'Helsinki'
}
const copiedUser = {...user}
console.log(copiedUser)
```
```sh
{name: "Asabeneh", title: "Programmer", country: "Finland", city: "Helsinki"}
```
Modifying or changing the object while copying
```js
const user = {
name:'Asabeneh',
title:'Programmer',
country:'Finland',
city:'Helsinki'
}
const copiedUser = {...user, title:'instructor'}
console.log(copiedUser)
```
```sh
{name: "Asabeneh", title: "instructor", country: "Finland", city: "Helsinki"}
```
#### Spread operator with arrow function
Whenever we like to write an arrow function which takes unlimited number of arguments we use a spread operator. If we use a spread operator as a parameter, the argument passed when we invoke a function will change to an array.
```js
const sumAllNums = (...args) => {
console.log(args)
}
sumAllNums(1, 2, 3,4,5)
```
```sh
[1, 2, 3, 4, 5]
```
```js
const sumAllNums = (...args) => {
let sum = 0
for (const num of args){
sum += num
}
return sum
}
console.log(sumAllNums(1, 2, 3,4,5))
```
```sh
15
```
🌕 You achieved quite a lot so far. Now, your level of JavaScript is upper intermediate. Keep going! You have just completed day 11 challenges and you are 11 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
### Exercises: Level 1
```js
const constants = [2.72, 3.14, 9.81, 37, 100]
const countries = ['Finland', 'Estonia', 'Sweden', 'Denmark', 'Norway']
const rectangle = {
width: 20,
height: 10,
area: 200,
perimeter: 60
}
const users = [
{
name:'Brook',
scores:75,
skills:['HTM', 'CSS', 'JS'],
age:16
},
{
name:'Alex',
scores:80,
skills:['HTM', 'CSS', 'JS'],
age:18
},
{
name:'David',
scores:75,
skills:['HTM', 'CSS'],
age:22
},
{
name:'John',
scores:85,
skills:['HTML'],
age:25
},
{
name:'Sara',
scores:95,
skills:['HTM', 'CSS', 'JS'],
age: 26
},
{
name:'Martha',
scores:80,
skills:['HTM', 'CSS', 'JS'],
age:18
},
{
name:'Thomas',
scores:90,
skills:['HTM', 'CSS', 'JS'],
age:20
}
]
```
1. Destructure and assign the elements of constants array to e, pi, gravity, humanBodyTemp, waterBoilingTemp.
2. Destructure and assign the elements of countries array to fin, est, sw, den, nor
3. Destructure the rectangle object by its properties or keys.
### Exercises: Level 2
1. Iterate through the users array and get all the keys of the object using destructuring
2. Find the persons who have less than two skills
### Exercises: Level 3
1. Destructure the countries object print name, capital, population and languages of all countries
2. A junior developer structure student name, skills and score in array of arrays which may not easy to read. Destructure the following array name to name, skills array to skills, scores array to scores, JavaScript score to jsScore and React score to reactScore variable in one line.
```js
const student = ['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]]
console.log(name, skills, jsScore, reactScore)
```
```sh
David (4) ["HTM", "CSS", "JS", "React"] 90 95
```
3. Write a function called *convertArrayToObject* which can convert the array to a structure object.
```js
const students = [
['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]],
['John', ['HTM', 'CSS', 'JS', 'React'], [85, 80, 85, 80]]
]
console.log(convertArrayToObject(students))
[
{
name: 'David',
skills: ['HTM','CSS','JS','React'],
scores: [98,85,90,95]
},
{
name: 'John',
skills: ['HTM','CSS','JS','React'],
scores: [85, 80,85,80]
}
]
```
4. Copy the student object to newStudent without mutating the original object. In the new object add the following ?
- Add Bootstrap with level 8 to the front end skill sets
- Add Express with level 9 to the back end skill sets
- Add SQL with level 8 to the data base skill sets
- Add SQL without level to the data science skill sets
```js
const student = {
name: 'David',
age: 25,
skills: {
frontEnd: [
{ skill: 'HTML', level: 10 },
{ skill: 'CSS', level: 8 },
{ skill: 'JS', level: 8 },
{ skill: 'React', level: 9 }
],
backEnd: [
{ skill: 'Node',level: 7 },
{ skill: 'GraphQL', level: 8 },
],
dataBase:[
{ skill: 'MongoDB', level: 7.5 },
],
dataScience:['Python', 'R', 'D3.js']
}
}
```
The copied object output should look like this:
```js
{
name: 'David',
age: 25,
skills: {
frontEnd: [
{skill: 'HTML',level: 10},
{skill: 'CSS',level: 8},
{skill: 'JS',level: 8},
{skill: 'React',level: 9},
{skill: 'BootStrap',level: 8}
],
backEnd: [
{skill: 'Node',level: 7},
{skill: 'GraphQL',level: 8},
{skill: 'Express',level: 9}
],
dataBase: [
{ skill: 'MongoDB',level: 7.5},
{ skill: 'SQL',level: 8}
],
dataScience: ['Python','R','D3.js','SQL']
}
}
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 10](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/10_Day/10_day_Set_and_Map.md) | [Day 12>>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/12_Day/12_day_regular_expressions.md)