Merge pull request #2 from Asabeneh/master

updating my challenge branch
pull/52/head
Carlos Mario Mora Restrepo 6 years ago committed by GitHub
commit 5bfd4215b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

7
.gitignore vendored

@ -3,6 +3,7 @@ playground
/playground /playground
.DS_Store .DS_Store
test.js test.js
res.md
day3.md day3.md
day4.md day4.md
day5.md day5.md
@ -13,10 +14,6 @@ day9.md
day10.md day10.md
01_02_03_days_backup.md 01_02_03_days_backup.md
test.md test.md
06_Day
07_Day
08_Day
09_Day
10_Day
11_Day 11_Day
12_Day 12_Day
test.html

@ -6,6 +6,8 @@
</head> </head>
<body> <body>
<h1>30DaysOfJavaScript:03 Day</h1>
<h2>Introduction</h2>
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button> <button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button>
<script src="./helloworld.js"></script> <script src="./helloworld.js"></script>
<script src="./introduction.js"></script> <script src="./introduction.js"></script>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

@ -0,0 +1,17 @@
// Declaring different variables of different data types
let firstName = 'Asabeneh' // first name of a person
let lastName = 'Yetayeh' // last name of a person
let country = 'Finland' // country
let city = 'Helsinki' // capital city
let age = 100 // age in years
let isMarried = true
// Declaring variables with number values
const gravity = 9.81 // earth gravity in m/s2
const boilingPoint = 100 // water boiling point, temperature in oC
const PI = 3.14 // geometrical constant
// Variables can also be declaring in one line separated by comma
let name = 'Asabeneh', //name of a person
job = 'teacher',
live = 'Finland'

@ -1,10 +1,22 @@
<div align="center">
## Table of Contents <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>
</div>
[<< Day 1](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/readMe.md) | [Day 3 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_booleans_operators_date.md) [<< Day 1](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/readMe.md) | [Day 3 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_booleans_operators_date.md)
--
![Thirty Days Of JavaScript](./day_1_2.png) ![Thirty Days Of JavaScript](../images/banners/day_1_2.png)
- [📔 Day 2](#%f0%9f%93%94-day-2) - [📔 Day 2](#%f0%9f%93%94-day-2)
- [Data types](#data-types) - [Data types](#data-types)
@ -311,7 +323,7 @@ Asabeneh Yetayeh. I am 250. I live in Finland
#### Long Literal Strings #### Long Literal Strings
A string could be a single character or paragraph or a page. If the string length is too big it does not fit in one line. We can use the backslash character (\) at the end of each line to indicate that the string will continue on the next line. A string could be a single character or paragraph or a page. If the string length is too big it does not fit in one line. We can use the backslash character (\\) at the end of each line to indicate that the string will continue on the next line.
**Example:** **Example:**
```js ```js
@ -762,7 +774,7 @@ console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
**Example:** **Example:**
```js ```js
// Different python data types // Different javascript data types
// Let's declare different data types // Let's declare different data types
let firstName = 'Asabeneh' // string let firstName = 'Asabeneh' // string
@ -862,7 +874,7 @@ let numInt = parseInt(num)
console.log(numInt) // 9 console.log(numInt) // 9
``` ```
🌕 You are awesome. You have just completed day 2 challenge and you are two steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. 🌕 You are awesome. You have just completed day 2 challenges and you are two steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
# 💻 Day 2: Exercises # 💻 Day 2: Exercises

@ -6,6 +6,8 @@
</head> </head>
<body> <body>
<h1>30DaysOfJavaScript:02 Day</h1>
<h2>Data types</h2>
<!-- import your scripts here --> <!-- import your scripts here -->
<script src="./main.js"></script> <script src="./main.js"></script>

@ -1,9 +1,21 @@
## Table of Contents <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 2](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/02_Day/02_day_data_types.md) | [Day 4 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/04_Day/04_day_conditionals.md) [<< Day 2](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/02_Day/02_day_data_types.md) | [Day 4 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/04_Day/04_day_conditionals.md)
--
![Thirty Days Of JavaScript](./day_1_3.png) ![Thirty Days Of JavaScript](../images/banners/day_1_3.png)
- [📔 Day 3](#%f0%9f%93%94-day-3) - [📔 Day 3](#%f0%9f%93%94-day-3)
- [Booleans](#booleans) - [Booleans](#booleans)
@ -190,7 +202,7 @@ console.log(0 === false) // false, not exactly the same
console.log(1 == true) // true, equivalent console.log(1 == true) // true, equivalent
console.log(1 === true) // false, not exactly the same console.log(1 === true) // false, not exactly the same
console.log(undefined == null) // true console.log(undefined == null) // true
console.log(undefined === null) // true console.log(undefined === null) // false
console.log(NaN == NaN) // false, not equal console.log(NaN == NaN) // false, not equal
console.log(NaN === NaN) // false console.log(NaN === NaN) // false
console.log(typeof NaN) // number console.log(typeof NaN) // number
@ -207,7 +219,7 @@ console.log('python'.length > 'dragon'.length) // false
Try to understand the above comparisons with some logic. Remember without any logic might be difficult. Try to understand the above comparisons with some logic. Remember without any logic might be difficult.
JavaScript is some how a wired kind of programming language. JavaScript code run and give you a result but unless you are good at it may not be the desired result. JavaScript is some how a wired kind of programming language. JavaScript code run and give you a result but unless you are good at it may not be the desired result.
As rule of thumb, if a value is not true with == it will not be equall with ===. Using === is safer than using ===. The following [link](https://dorey.github.io/JavaScript-Equality-Table/) has an exhaustive list of comparison of data types. As rule of thumb, if a value is not true with == it will not be equal with ===. Using === is safer than using ==. The following [link](https://dorey.github.io/JavaScript-Equality-Table/) has an exhaustive list of comparison of data types.
### Logical Operators ### Logical Operators
@ -307,17 +319,17 @@ No need for a rain coat.
let number = 5 let number = 5
number > 0 number > 0
? console.log(`${number} is a positive number`) ? console.log(`${number} is a positive number`)
: console.log(`${number} is a number number`) : console.log(`${number} is a negative number`)
number = -5 number = -5
number > 0 number > 0
? console.log(`${number} is a positive number`) ? console.log(`${number} is a positive number`)
: console.log(`${number} is a number number`) : console.log(`${number} is a negative number`)
``` ```
```sh ```sh
5 is a positive number 5 is a positive number
-5 is a number number -5 is a negative number
``` ```
### Operator Precendence ### Operator Precendence
@ -481,7 +493,7 @@ const minutes = now.getMinutes() // return number (0 -59)
console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56 console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
``` ```
🌕 You have boundless energy. You have just completed day 3 challenge and you are three steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. 🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
# 💻 Day 3: Exercises # 💻 Day 3: Exercises

@ -6,6 +6,8 @@
</head> </head>
<body> <body>
<h1>30DaysOfJavaScript:03 Day</h1>
<h2>Booleans, undefined, null, date object</h2>
<!-- import your scripts here --> <!-- import your scripts here -->
<script src="./scripts/main.js"></script> <script src="./scripts/main.js"></script>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

@ -1,15 +1,27 @@
## Table of Contents <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 3](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_booleans_operators_date.md) | [Day 5 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/05_Day/05_day_arrays.md) [<< Day 3](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/03_Day/03_booleans_operators_date.md) | [Day 5 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/05_Day/05_day_arrays.md)
--
![Thirty Days Of JavaScript](./day_1_4.png) ![Thirty Days Of JavaScript](../images/banners/day_1_4.png)
- [📔 Day 4](#%f0%9f%93%94-day-4) - [📔 Day 4](#%f0%9f%93%94-day-4)
- [Conditionals](#conditionals) - [Conditionals](#conditionals)
- [if](#if) - [if](#if)
- [if else](#if-else) - [if else](#if-else)
- [if else if else else](#if-else-if-else-else) - [if else if else](#if-else-if-else)
- [Switch](#switch) - [Switch](#switch)
- [Ternary Operators](#ternary-operators) - [Ternary Operators](#ternary-operators)
- [💻 Exercise : Conditionals](#%f0%9f%92%bb-exercise--conditionals) - [💻 Exercise : Conditionals](#%f0%9f%92%bb-exercise--conditionals)
@ -113,7 +125,7 @@ if (isRaining) {
The above condition is false, therefore the else block was executed. How about if our condition is more than two, we will use *else if* conditions. The above condition is false, therefore the else block was executed. How about if our condition is more than two, we will use *else if* conditions.
### if else if else else ### if else if else
On our daily life, we make decision on daily basis. We make decision not by checking one or two conditions instead we make decisions based on multiple conditions. As similar to our daily life, programming is also full conditions. We use *else if* when we have multiple conditions. On our daily life, we make decision on daily basis. We make decision not by checking one or two conditions instead we make decisions based on multiple conditions. As similar to our daily life, programming is also full conditions. We use *else if* when we have multiple conditions.
@ -193,9 +205,11 @@ switch (weather) {
default: default:
console.log(' No need for rain coat.') console.log(' No need for rain coat.')
} }
// Switch More Examples // Switch More Examples
var dayUserInput = prompt('What day is today ?') let dayUserInput = prompt('What day is today ?')
var day = dayUserInput.toLowerCase() let day = dayUserInput.toLowerCase()
switch (day) { switch (day) {
case 'monday': case 'monday':
console.log('Today is Monday') console.log('Today is Monday')
@ -218,10 +232,10 @@ switch (day) {
case 'sunday': case 'sunday':
console.log('Today is Sunday') console.log('Today is Sunday')
break break
default: default:
console.log('It is not a week day.') console.log('It is not a week day.')
} }
``` ```
### Ternary Operators ### Ternary Operators
@ -235,7 +249,7 @@ isRaining
: console.log('No need for a rain coat.') : console.log('No need for a rain coat.')
``` ```
🌕 You are extraordinary and you have a remarkable potential. You have just completed day 4 challenge and you are four steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. 🌕 You are extraordinary and you have a remarkable potential. You have just completed day 4 challenges and you are four steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
# 💻 Exercise : Conditionals # 💻 Exercise : Conditionals
@ -289,7 +303,7 @@ isRaining
Enter a number: 2 Enter a number: 2
2 is an even number 2 is an even number
Enter a number 9 Enter a number: 9
9 is is an odd number. 9 is is an odd number.
``` ```

@ -1,15 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript</title>
</head>
<body>
<!-- import your scripts here -->
<script src="./scripts/main.js"></script>
</body>
</html>

@ -2,7 +2,7 @@
<html> <html>
<head> <head>
<title>30DaysOfJavaScript:04 Day</title> <title>30DaysOfJavaScript</title>
</head> </head>
<body> <body>

@ -1 +1,3 @@
// this is your main.js script // this is your main.js script
alert('Open the browser console whenever you work on JavaScript')

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

@ -1,7 +1,20 @@
## Table of Contents <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 4](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/04_Day/04_day_conditionals.md) | [Day 6 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/06_Day/06_day_loops.md)
[<< Day 4](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/04_Day/04_day_conditionals.md) | [Day 6 >>](#)
--
![Day 5](../images/banners/day_1_5.png) ![Day 5](../images/banners/day_1_5.png)
- [📔 Day 5](#%f0%9f%93%94-day-5) - [📔 Day 5](#%f0%9f%93%94-day-5)
@ -29,19 +42,21 @@
- [Add an element from the beginning](#add-an-element-from-the-beginning) - [Add an element from the beginning](#add-an-element-from-the-beginning)
- [Reversing array order](#reversing-array-order) - [Reversing array order](#reversing-array-order)
- [Sorting elements in array](#sorting-elements-in-array) - [Sorting elements in array](#sorting-elements-in-array)
- [Array of arrays](#array-of-arrays)
- [💻 Exercise](#%f0%9f%92%bb-exercise) - [💻 Exercise](#%f0%9f%92%bb-exercise)
# 📔 Day 5 # 📔 Day 5
## Arrays ## Arrays
In contrast to variables array can store _multiple values_. Each value in an array has an _index_ and each index has _a reference in a memory address_. Each value can be accessed by using their _indexes_. The index of an array starts from _zero_ and the last element is less by one from the length of the array. In contrast to variables, an array can store _multiple values_. Each value in an array has an _index_, and each index has _a reference in a memory address_. Each value can be accessed by using their _indexes_. The index of an array starts from _zero_, and the last element is less by one from the length of the array.
Array is a collection of different data types which are ordered and changeable(modifiable). Allows duplicate element and different data types. An array can be empty or it may have different data type values An array is a collection of different data types which are ordered and changeable(modifiable). An array allows storing duplicate elements and different data types. An array can be empty, or it may have different data type values.
### How to create an empty array ### How to create an empty array
In JavaScript we can create array in different ways. Let us different ways to create an array. In JavaScript, we can create an array in different ways. Let us different ways to create an array.
It is very common to use *const* instead of *let* to declare an array variable. If you ar using const it means you do not use that name again.
- Using Array constructor - Using Array constructor
@ -125,7 +140,7 @@ console.log(arr)
### Creating an array using split ### Creating an array using split
As we have seen in earlier section, we can split a string at different position and we can change to an array. Let us see the examples blow. As we have seen in the earlier section, we can split a string at different positions, and we can change to an array. Let us see the examples below.
```js ```js
let js = 'JavaScript' let js = 'JavaScript'
@ -148,7 +163,7 @@ console.log(words)
### Accessing array items using index ### Accessing array items using index
We access each element in an array using their index. An array index start from 0. The picture below show clearly the starting of the index. We access each element in an array using their index. An array index starts from 0. The picture below clearly shows the starting of the index.
![arr index](../images/array_index.png) ![arr index](../images/array_index.png)
@ -167,6 +182,7 @@ console.log(lastFruit) // lemon
let lastIndex = fruits.length - 1 let lastIndex = fruits.length - 1
lastFruit = fruits[lastIndex] lastFruit = fruits[lastIndex]
console.log(lastFruit) // lemon console.log(lastFruit) // lemon
``` ```
@ -247,7 +263,7 @@ console.log(shoppingCart[lastIndex]) // -> Sugar
### Modifying array element ### Modifying array element
An array is mutable(modifiable). Once an array is created we can modify the contents or the array elements. An array is mutable(modifiable). Once an array is created, we can modify the contents of the array elements.
```js ```js
const numbers = [1, 2, 3, 4, 5] const numbers = [1, 2, 3, 4, 5]
@ -283,7 +299,7 @@ console.log(countries)
### Methods to manipulate array ### Methods to manipulate array
There are different methods to manipulate an array. These are some of the available methods to deal with arrays:_Array,length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift_ There are different methods to manipulate an array. These are some of the available methods to deal with arrays:_Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift_
#### Array Constructor #### Array Constructor
@ -305,13 +321,13 @@ fill: Fill all the array elements with a static value
const arr = Array() // creates an an empty array const arr = Array() // creates an an empty array
console.log(arr) console.log(arr)
const eightXvalues = Array(8).fill('X') // it creates eight element values const eightXvalues = Array(8).fill('X') // it creates eight element values filled with 'X'
console.log(eightXvalues) // ['X', 'X','X','X','X','X','X','X'] console.log(eightXvalues) // ['X', 'X','X','X','X','X','X','X']
const eight0values = Array(8).fill(0) // it creates eight element values const eight0values = Array(8).fill(0) // it creates eight element values filled with '0'
console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0] console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0]
const four4values = Array(4).fill(4) // it creates 4 element values const four4values = Array(4).fill(4) // it creates 4 element values filled with '4'
console.log(four4values) // [4, 4, 4, 4, 4, 4, 4, 4] console.log(four4values) // [4, 4, 4, 4, 4, 4, 4, 4]
``` ```
@ -328,9 +344,9 @@ console.log(thirdList) // [1, 2, 3, 4, 5, 6]
``` ```
```js ```js
const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of fruits const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of fruits
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of vegetables const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of vegetables
const fruitsAndVegetables = fruits.concat(vegetables) const fruitsAndVegetables = fruits.concat(vegetables) // concatenate the two arrays
console.log(fruitsAndVegetables) console.log(fruitsAndVegetables)
``` ```
@ -345,7 +361,7 @@ Length:To know the size of the array
```js ```js
const numbers = [1, 2, 3, 4, 5] const numbers = [1, 2, 3, 4, 5]
console.log(numbers.length) // -> 5 console.log(numbers.length) // -> 5 is the size of the array
``` ```
#### Getting index an element in arr array #### Getting index an element in arr array
@ -361,7 +377,7 @@ console.log(numbers.indexOf(1)) // -> 0
console.log(numbers.indexOf(6)) // -> -1 console.log(numbers.indexOf(6)) // -> -1
``` ```
Check an element if it exist in an array Check an element if it exist in an array.
- Check items in a list - Check items in a list
@ -382,7 +398,7 @@ if(index != -1){
index != -1 ? console.log('This fruit does exist in the array'): console.log('This fruit does not exist in the array') index != -1 ? console.log('This fruit does exist in the array'): console.log('This fruit does not exist in the array')
// let us check if a avocado exist in the array // let us check if a avocado exist in the array
let indexOfAvocado = fruits.indexOf('avocado') // -1 let indexOfAvocado = fruits.indexOf('avocado') // -1, if the element not found index is -1
if(indexOfAvocado!= -1){ if(indexOfAvocado!= -1){
console.log('This fruit does exist in the array') console.log('This fruit does exist in the array')
} else { } else {
@ -393,12 +409,12 @@ if(indexOfAvocado!= -1){
#### Getting last index of an element in array #### Getting last index of an element in array
lastIndexOf:Give the position of the last item in the array. If it exist it returns the index else it returns -1. lastIndexOf: It gives the position of the last item in the array. If it exist, it returns the index else it returns -1.
```js ```js
const numbers = [1, 2, 3, 4, 5, 3, 1, 2] const numbers = [1, 2, 3, 4, 5, 3, 1, 2]
console.log(numbers.lastIndexOf(2)) // -7 console.log(numbers.lastIndexOf(2)) // 7
console.log(numbers.lastIndexOf(0)) // -1 console.log(numbers.lastIndexOf(0)) // -1
console.log(numbers.lastIndexOf(1)) // 6 console.log(numbers.lastIndexOf(1)) // 6
console.log(numbers.lastIndexOf(4)) // 3 console.log(numbers.lastIndexOf(4)) // 3
@ -455,7 +471,7 @@ console.log(names.toString()) // Asabeneh,Mathias,Elias,Brook
#### Joining array elements #### Joining array elements
join:To join the elements of the array, the argument passed in the join method will be joined in the array and return as a string. By default it joins with a comma but we can pass different string parameter which can be joined between the items. join: It used to join the elements of the array, the argument passed in the join method will be joined in the array and return as a string. By default, it joins with a comma, but we can pass different string parameter which can be joined between the items.
```js ```js
const numbers = [1, 2, 3, 4, 5] const numbers = [1, 2, 3, 4, 5]
@ -485,7 +501,7 @@ console.log(webTechs.join(' # ')) // "HTML # CSS # JavaScript # React # Redux #
#### Slice array elements #### Slice array elements
Slice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position Slice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position.
```js ```js
const numbers = [1,2,3,4,5] const numbers = [1,2,3,4,5]
@ -498,20 +514,28 @@ Slice: To cut out a multiple items in range. It takes two parameters:starting an
#### Splice method in array #### Splice method in array
Splice: It takes three parameters:Starting position, number of times to be removed and number items to be added. Splice: It takes three parameters:Starting position, number of times to be removed and number of items to be added.
```js ```js
const numbers = [1, 2, 3, 4, 5]; const numbers = [1, 2, 3, 4, 5]
console.log(numbers.splice()) // -> remove all items console.log(numbers.splice()) // -> remove all items
```
```js
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.splice(0,1)) // remove the first item console.log(numbers.splice(0,1)) // remove the first item
console.log(numbers.splice(3, 3, 6, 7, 8)) // -> [1,2,6,7,8] //it removes two item and replace three items ```
```js
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.splice(3, 3, 6, 7, 8)) // -> [1, 2, 3, 6, 7, 8] //it removes two item and replace three items
``` ```
#### Adding item to an array using push #### Adding item to an array using push
Push: adding item in the end. To add item to the end of an existing array we use the push method Push: adding item in the end. To add item to the end of an existing array we use the push method.
```js ```js
// syntax // syntax
@ -544,7 +568,7 @@ console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']
#### Removing the end element using pop #### Removing the end element using pop
Pop: Removing item in the end pop: Removing item in the end.
```js ```js
const numbers = [1, 2, 3, 4, 5] const numbers = [1, 2, 3, 4, 5]
@ -555,7 +579,7 @@ console.log(numbers) // -> [1,2,3,4]
#### Removing an element from the beginning #### Removing an element from the beginning
shift: Removing one array element in the beginning of the array shift: Removing one array element in the beginning of the array.
```js ```js
const numbers = [1, 2, 3, 4, 5] const numbers = [1, 2, 3, 4, 5]
@ -566,7 +590,7 @@ console.log(numbers) // -> [2,3,4,5]
#### Add an element from the beginning #### Add an element from the beginning
unshift: Adding array element in the beginning of the array unshift: Adding array element in the beginning of the array.
```js ```js
const numbers = [1, 2, 3, 4, 5] const numbers = [1, 2, 3, 4, 5]
@ -577,7 +601,7 @@ console.log(numbers) // -> [0,1,2,3,4,5]
#### Reversing array order #### Reversing array order
reverse: reverse the order of an array reverse: reverse the order of an array.
```js ```js
const numbers = [1, 2, 3, 4, 5] const numbers = [1, 2, 3, 4, 5]
@ -591,7 +615,7 @@ console.log(numbers) // [1, 2, 3, 4, 5]
#### Sorting elements in array #### Sorting elements in array
sort: arrange array elements in ascending order. Sort takes a call back function, we wil see how we use sort with call back function in the coming sections. sort: arrange array elements in ascending order. Sort takes a call back function, we will see how we use sort with call back function in the coming sections.
```js ```js
const webTechs = [ const webTechs = [
@ -611,7 +635,27 @@ webTechs.reverse() // after sorting we can reverse it
console.log(webTechs) // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"] console.log(webTechs) // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"]
``` ```
🌕 You are diligent and you have already achieved quite a lot. You have just completed day 5 challenge and you are 5 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. ### Array of arrays
Array can store different data types including an array itself. Let us create an array of arrays
```js
const firstNums = [1, 2, 3]
const secondNums = [1, 4, 9]
const arrayOfArray = [[1, 2, 3], [1, 2, 3]]
console.log(arrayOfArray[0]) // [1, 2, 3]
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
const backEnd = ['Node','Express', 'MongoDB']
const fullStack = [frontEnd, backEnd]
console.log(fullStack) // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]]
console.log(fullStack.length) // 2
console.log(fullStack[0]) // ["HTML", "CSS", "JS", "React", "Redux"]
console.log(fullStack[1]) // ["Node", "Express", "MongoDB"]
```
🌕 You are diligent and you have already achieved quite a lot. You have just completed day 5 challenges and you are 5 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercise ## 💻 Exercise
@ -690,7 +734,7 @@ const webTechs = [
- Remove 'Honey' if you are allergic to honey - Remove 'Honey' if you are allergic to honey
- modify tea to 'Green Tea' - modify tea to 'Green Tea'
1. In countries array check if 'Ethiopia' exists in the array if it exists print 'ETHIOPIA'. If it does not exist add to the countries list. 1. In countries array check if 'Ethiopia' exists in the array if it exists print 'ETHIOPIA'. If it does not exist add to the countries list.
1. In the webTechs array check if Sass exists in the array if it exists print 'Sass is a CSS preprocess'. If it does not exist add Sass to the array. 1. In the webTechs array check if Sass exists in the array and if it exists print 'Sass is a CSS preprocess'. If it does not exist add Sass to the array and print the array.
1. Concatenate the following two variables and store it in a fullStack variable. 1. Concatenate the following two variables and store it in a fullStack variable.
```js ```js
@ -704,7 +748,7 @@ const webTechs = [
["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]
``` ```
1. The following is a list of 10 students ages: 1. The following is an array of 10 students ages:
```js ```js
const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24] const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
@ -716,9 +760,11 @@ const webTechs = [
- Find the average age(all items divided by number of items) - Find the average age(all items divided by number of items)
- Find the range of the ages(max minus min) - Find the range of the ages(max minus min)
- Compare the value of (min - average) and (max - average), use *abs()* method - Compare the value of (min - average) and (max - average), use *abs()* method
1. Find the middle country(ies) in the [countries list](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) 1.Slice the first ten countries from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. Divide the countries list into two equal lists if it is even. If countries array is not even one more country for the first half. 1. Find the middle country(ies) in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. Find the middle country(ies) in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. Divide the countries array into two equal arrays if it is even. If countries array is not even , one more country for the first half.
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 4](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/04_Day/04_day_conditionals.md) | [Day 6 >>](#) [<< Day 4](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/04_Day/04_day_conditionals.md) | [Day 6 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/06_Day/06_day_loops.md)

@ -6,6 +6,8 @@
</head> </head>
<body> <body>
<h1>30DaysOfJavaScript:05 Day</h1>
<h2>Arrays</h2>
<script src="./data/countries.js"></script> <script src="./data/countries.js"></script>
<script src="./scripts/main.js"></script> <script src="./scripts/main.js"></script>

@ -1,2 +1,3 @@
console.log(countries) console.log(countries)
alert('Open the browser console whenever you work on JavaScript')
alert('Open the console and check if the countries has been loaded') alert('Open the console and check if the countries has been loaded')

@ -0,0 +1,439 @@
<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 5](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/05_Day/05_day_arrays.md) | [Day 7 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/07_Day/07_day_functions.md)
![Day 5](../images/banners/day_1_6.png)
- [📔 Day 6](#%f0%9f%93%94-day-6)
- [Loops](#loops)
- [for Loop](#for-loop)
- [while loop](#while-loop)
- [do while loop](#do-while-loop)
- [for of loop](#for-of-loop)
- [break](#break)
- [continue](#continue)
- [💻 Exercises:Day 6](#%f0%9f%92%bb-exercisesday-6)
# 📔 Day 6
## Loops
Most of the activities we do in life are full of repetitions. Imagine if I ask you to print out from 0 to 100 using console.log(). To implement this simple task it may take you 2 to 5 minutes, such kind of tedious and repetitive task can be carried out using loop.
In programming languages to carry out repetitive task we use different kinds of loop. The following examples are the commonly used loops.
### for Loop
```js
//For loop structure
for(initialization, condition, increment/decrement){
// code goes here
}
```
```js
for(let i = 0; i <= 5; i++){
console.log(i)
}
// 0 1 2 3 4 5
```
```js
for(let i = 5; i >= 0; i--){
console.log(i)
}
// 5 4 3 2 1 0
```
```js
for(let i = 0; i <= 5; i++){
console.log(`${i} * ${i} = ${i * i}`)
}
```
```sh
0 * 0 = 0
1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
5 * 5 = 25
```
```js
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']
const newArr = []
for(let i = 0; i < countries.length; i++){
newArr.push(countries[i].toUpperCase())
}
//["FINLAND", "SWEDEN", "DENMARK", "NORWAY", "ICELAND"]
```
Adding all elements in the array
```js
const numbers = [1, 2, 3, 4, 5]
let sum = 0
for(let i = 0; i < numbers.length; i++){
sum = sum + numbers[i] // can be shorten, sum += numbers[i]
}
console.log(sum) // 15
```
Creating a new array based on the existing array
```js
const numbers = [1, 2, 3, 4, 5]
const newArr = []
let sum = 0
for(let i = 0; i < numbers.length; i++){
newArr.push(i * i)
}
console.log(newArr) // [1, 4, 9, 16, 25]
```
```js
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
const newArr = []
for(let i = 0; i < countries.length; i++){
newArr.push(countries[i].toUpperCase())
}
console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
```
### while loop
```js
let i = 0
while (i <= 5) {
console.log(i)
i++
}
// 0 1 2 3 4 5
```
### do while loop
```js
let i = 0
do {
console.log(i)
i++
} while (i <= 5)
// 0 1 2 3 4 5
```
### for of loop
We use for of loop for arrays. It is very hand way to iterate through an array if we are not interested in the index.
```js
for (const element of arr) {
// code goes here
}
```
```js
const numbers = [1, 2, 3, 4, 5]
for (const num of numbers) {
console.log(num) //1 2 3 4 5
}
for (const num of numbers) {
console.log(num * num) //1 4 9 16 25
}
// adding all the numbers in the array
let sum = 0
for (const num of numbers) {
sum += sum + num // can be also shorten like this, sum += num
}
console.log(sum) // 15
const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB'
]
for (const tech of webTechs) {
console.log(tech.toUpperCase()) // HTML CSS JAVASCRIPT REACT NODE MONGODB
}
for (const tech of webTechs) {
console.log(tech[0]) //get only the first letter of each element, H C J R N M
}
```
```js
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
const newArr = []
for(const country of countries){
newArr.push(country.toUpperCase())
}
console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
```
### break
content will be added soon
### continue
content will added soon
🌕 You are so brave, you made it to this far. Now, you have gained the power to automate repetitive and tedious tasks. You have just completed day 6 challenges and you are 6 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises:Day 6
```js
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya'
]
const webTechs = [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB'
]
const mernStack = ['MongoDB', 'Express', 'React', 'Node']
```
1. Iterate 0 to 10 using for loop, do the same using while and do while loop
2. Iterate 10 to 0 using for loop, do the same using while and do while loop
3. Iterate 0 to n using for loop
4. Write a loop that makes the following pattern using console.log():
```js
#
##
###
####
#####
######
#######
```
5. Use loop to print the following pattern:
```sh
0 x 0 = 0
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
5 x 5 = 25
6 x 6 = 36
7 x 7 = 49
8 x 8 = 64
9 x 9 = 81
10 x 10 = 100
```
6. Using loop print the following pattern
```sh
i i^2 i^3
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
```
7. Use for loop to iterate from 0 to 100 and print only even numbers
8. Use for loop to iterate from 0 to 100 and print only odd numbers
9. Use for loop to iterate from 0 to 100 and print only prime numbers
10. Use for loop to iterate from 0 to 100 and print and print the sum of all numbers.
```sh
The sum all numbers is 5050.
```
11. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.
```sh
The sum of all evens is 2550. And the sum of all odds is 2500.
```
12. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds. Print sum of evens and sum of odds as array
```sh
[2550, 2500]
```
13. Develop a small script which generate array of 5 random numbers
14. Develop a small script which generate array of 5 random numbers and the numbers must be unique
15. Develop a small script which generate a six characters random id:
```sh
5j2khz
```
16. Develop a small script which generate any number of characters random id:
```sh
fe3jo1gl124g
```
```sh
xkqci4utda1lmbelpkm03rba
```
17. Write a script which generates a random hexadecimal number.
```sh
'#ee33df'
```
18. Write a script which generates a random rgb color number.
```sh
rgb(240,180,80)
```
19. Using the above countries array, create the following new array.
```sh
["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"]
```
20. Using the above countries array, create an array for countries length'.
```sh
[7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5]
```
21. Use the countries array to create the following array of arrays:
```sh
[
['Albania', 'ALB', 7],
['Bolivia', 'BOL', 7],
['Canada', 'CAN', 6],
['Denmark', 'DEN', 7],
['Ethiopia', 'ETH', 8],
['Finland', 'FIN', 7],
['Germany', 'GER', 7],
['Hungary', 'HUN', 7],
['Ireland', 'IRE', 7],
['Japan', 'JAP', 5],
['Kenya', 'KEN', 5]
]
```
22. In above countries array, check if there is a country or countries containing the word 'land'. If there are countries containing 'land', print it as array. If there is no country containing the word 'land', print 'These are countries without land'.
```sh
['Finland', 'Iceland']
```
23. In above countries array, check if there a country or countries end with a substring 'ia'. If there are countries end with, print it as array. If there is no country containing the word 'land', print 'These are countries ends without ia'.
```sh
['Albania', 'Bolivia','Ethiopia']
```
24. Using the above countries array, find the country containing the biggest number of characters.
```sh
Ethiopia
```
25. Using the above countries array, find the country containing only 5 characters.
```sh
['Japan', 'Kenya']
```
26. Find the longest word in the webTechs array
27. Use the webTechs are to create the following array of arrays:
```sh
[["HTML", 4], ["CSS", 3],["JavaScript", 10],["React", 5],["Redux", 5],["Node", 4],["MongoDB", 7]]
```
28. An application created using MongoDB, Express, React and Node is called a MERN stack. Create the acronym MERN by using the array mernStack
29. Iterate through the array, ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] using a for loop or for of loop and print out the items.
30. This is a fruit array , ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop without using a reverse method.
31. Print all the elements of array as shown below.
```js
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]
````
```sh
HTML
CSS
JS
REACT
NODE
EXPRESS
MONGODB
```
32. Copy countries array(Avoid mutation)
33. Arrays are mutable. Create a copy of array which does not modify the original. Sort the copied array and store in a variable sortedCountries
34. Sort the webTechs array and mernStack array
35. Extract all the countries contain the word 'land' from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
36. Find the country containing the hightest number of characters in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
37. Extract all the countries contain the word 'land' from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
38. Extract all the countries containing only four characters from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
39. Extract all the countries containing two or more words from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and print it as array
40. Reverse the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) and capitalize each country and stored it as an array
🎉 CONGRATULATIONS ! 🎉
[<< Day 5](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/05_Day/05_day_arrays.md) | [Day 7 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/07_Day/07_day_functions.md)

@ -0,0 +1,195 @@
const countries = [
'Afghanistan',
'Albania',
'Algeria',
'Andorra',
'Angola',
'Antigua and Barbuda',
'Argentina',
'Armenia',
'Australia',
'Austria',
'Azerbaijan',
'Bahamas',
'Bahrain',
'Bangladesh',
'Barbados',
'Belarus',
'Belgium',
'Belize',
'Benin',
'Bhutan',
'Bolivia',
'Bosnia and Herzegovina',
'Botswana',
'Brazil',
'Brunei',
'Bulgaria',
'Burkina Faso',
'Burundi',
'Cambodia',
'Cameroon',
'Canada',
'Cape Verde',
'Central African Republic',
'Chad',
'Chile',
'China',
'Colombi',
'Comoros',
'Congo (Brazzaville)',
'Congo',
'Costa Rica',
"Cote d'Ivoire",
'Croatia',
'Cuba',
'Cyprus',
'Czech Republic',
'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic',
'East Timor (Timor Timur)',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Fiji',
'Finland',
'France',
'Gabon',
'Gambia, The',
'Georgia',
'Germany',
'Ghana',
'Greece',
'Grenada',
'Guatemala',
'Guinea',
'Guinea-Bissau',
'Guyana',
'Haiti',
'Honduras',
'Hungary',
'Iceland',
'India',
'Indonesia',
'Iran',
'Iraq',
'Ireland',
'Israel',
'Italy',
'Jamaica',
'Japan',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Korea, North',
'Korea, South',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Macedonia',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Mauritania',
'Mauritius',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepal',
'Netherlands',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Panama',
'Papua New Guinea',
'Paraguay',
'Peru',
'Philippines',
'Poland',
'Portugal',
'Qatar',
'Romania',
'Russia',
'Rwanda',
'Saint Kitts and Nevis',
'Saint Lucia',
'Saint Vincent',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Serbia and Montenegro',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'Spain',
'Sri Lanka',
'Sudan',
'Suriname',
'Swaziland',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Togo',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Vatican City',
'Venezuela',
'Vietnam',
'Yemen',
'Zambia',
'Zimbabwe'
]

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:06 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:06 Day</h1>
<h2>Loops</h2>
<script src="./data/countries.js"></script>
<script src="./scripts/main.js"></script>
</body>
</html>

@ -0,0 +1,2 @@
console.log(countries)
alert('Open the console and check if the countries has been loaded')

@ -0,0 +1,680 @@
<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 6](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/06_Day/06_day_loops.md) | [Day 8 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/08_Day/08_day_objects.md)
![Thirty Days Of JavaScript](../images/banners/day_1_7.png)
- [📔 Day 7](#%f0%9f%93%94-day-7)
- [Functions](#functions)
- [Function Declaration](#function-declaration)
- [Function without a parameter and return](#function-without-a-parameter-and-return)
- [Function returning value](#function-returning-value)
- [Function with a parameter](#function-with-a-parameter)
- [Function with two parameters](#function-with-two-parameters)
- [Function with many parameters](#function-with-many-parameters)
- [Function with unlimited number of parameters](#function-with-unlimited-number-of-parameters)
- [Unlimited number of parameters in regular function](#unlimited-number-of-parameters-in-regular-function)
- [Unlimited number of parameters in arrow function](#unlimited-number-of-parameters-in-arrow-function)
- [Anonymous Function](#anonymous-function)
- [Expression Function](#expression-function)
- [Self Invoking Functions](#self-invoking-functions)
- [Arrow Function](#arrow-function)
- [Function with default parameters](#function-with-default-parameters)
- [Function declaration versus Arrow function](#function-declaration-versus-arrow-function)
- [💻 Exercises](#%f0%9f%92%bb-exercises)
# 📔 Day 7
## Functions
So far we have seen many builtin JavaScript functions. In this section, we will focus on custom functions. What is a function? Before we start making functions, lets understand what function is and why we need function?
A function is a reusable block of code or programming statements designed to perform a certain task.
A function is declared by a function key word followed by a name, followed by parentheses (). A parentheses can take a parameter. If a function take a parameter it will be called with argument. A function can also take a default parameter. To store a data to a function, a function has to return certain data types. To get the value we call or invoke a function.
Function makes code:
- clean and easy to read
- reusable
- easy to test
A function can be declared or created in couple of ways:
- _Declaration function_
- _Expression function_
- _Anonymous function_
- _Arrow function_
### Function Declaration
Let us see how to declare a function and how to call a function.
```js
//declaring a function without a parameter
function functionName() {
// code goes here
}
functionName() // calling function by its name and with parentheses
```
### Function without a parameter and return
Function can be declared without a parameter.
**Example:**
```js
// function without parameter, a function which square a number
function square() {
let num = 2
let sq = num * num
console.log(sq)
}
square() // 4
// function without parameter
function addTwoNumbers() {
let numOne = 10
let numTwo = 20
let sum = numOne + numTwo
console.log(sum)
}
addTwoNumbers() // function has to be called to be executed by it name
```
```js
function generateFullName (){
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let space = ' '
let fullName = firstName + space + lastName
console.log(fullName)
}
generateFullName() // calling a function
```
### Function returning value
Function can also return values, if a function does not return values the value of the function is undefined. Let us write the above functions with return. From now on, we return value to a function instead of printing it.
```js
function generateFullName (){
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(generateFullName())
```
```js
function addTwoNumbers() {
let numOne = 2
let numTwo = 3
let total = numOne + numTwo
return total
}
console.log(addTwoNumbers())
```
### Function with a parameter
In a function we can pass different data types(number, string, boolean, object, function) as a parameter.
```js
// function with one parameter
function functionName(parm1) {
//code goes her
}
functionName(parm1) // during calling or invoking one argument needed
function areaOfCircle(r) {
let area = Math.PI * r * r
return area
}
console.log(areaOfCircle(10)) // should be called with one argument
function square(number) {
return number * number
}
console.log(square(10))
```
### Function with two parameters
```js
// function with two parameters
function functionName(parm1, parm2) {
//code goes her
}
functionName(parm1, parm2) // during calling or invoking two arguments needed
// Function without parameter doesn't take input, so lets make a parameter with parameter
function sumTwoNumbers(numOne, numTwo) {
let sum = numOne + numTwo
console.log(sum)
}
sumTwoNumbers(10, 20) // calling functions
// If a function doesn't return it doesn't store data, so it should return
function sumTwoNumbersAndReturn(numOne, numTwo) {
let sum = numOne + numTwo
return sum
}
console.log(sumTwoNumbersAndReturn(10, 20))
function printFullName(firstName, lastName) {
return `${firstName} ${lastName}`
}
console.log(printFullName('Asabeneh', 'Yetayeh'))
```
### Function with many parameters
```js
// function with multiple parameters
function functionName(parm1, parm2, parm3,...){
//code goes here
}
functionName(parm1,parm2,parm3,...) // during calling or invoking three arguments needed
// this function takes array as a parameter and sum up the numbers in the array
function sumArrayValues(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum = sum + numbers[i];
}
return sum;
}
const numbers = [1, 2, 3, 4, 5];
//calling a function
console.log(sumArrayValues(numbers));
const areaOfCircle = (radius) => {
let area = Math.PI * radius * radius;
return area;
}
console.log(areaOfCircle(10))
```
### Function with unlimited number of parameters
Sometimes we do not know how many arguments the user going to pass. Therefore, we should know how to write a function which can take unlimited number of arguments. The way we do it has a significant difference between a function declaration(regular function) and arrow function.Let us see examples both in function declaration and arrow function.
#### Unlimited number of parameters in regular function
A function declaration provides a function scoped arguments array like object. Any thing we passed as argument in the function can be accessed from arguments object inside the functions. Let us see an example
```js
// Let us access the arguments object
function sumAllNums() {
console.log(arguments)
}
sumAllNums(1, 2, 3, 4))
// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
```
```js
// function declaration
function sumAllNums() {
let sum = 0
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i]
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4)) // 10
console.log(sumAllNums(10, 20, 13, 40, 10)) // 93
console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173
```
#### Unlimited number of parameters in arrow function
Arrow function does not have the function scoped arguments object. To implement a function which takes unlimited number of arguments in an arrow function we use spread operator followed by any parameter name. Any thing we passed as argument in the function can be accessed as array in the arrow function. Let us see an example
```js
// Let us access the arguments object
const sumAllNums = (...args) => {
// console.log(arguments), arguments object not found in arrow function
// instead we use an a parameter followed by spread operator
console.log(args)
}
sumAllNums(1, 2, 3, 4))
// [1, 2, 3, 4]
```
```js
// function declaration
const sumAllNums = (...args) => {
let sum = 0
for (const element of args) {
sum += element
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4)) // 10
console.log(sumAllNums(10, 20, 13, 40, 10)) // 93
console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173
```
### Anonymous Function
Anonymous function or without name
```js
const anonymousFun = function() {
console.log(
'I am an anonymous function and my value is stored in anonymousFun'
)
}
```
### Expression Function
Expression functions are anonymous functions. After we create a function without a name and with assign it to a variable. To return a value from the function we should call the variable. Look at the example below.
```js
//Declaration function
function square(n) {
return n * n
}
console.log(square(2)) // -> 4
// Function expression
const square = function(n) {
return n * n
}
console.log(square(2)) // -> 4
```
### Self Invoking Functions
Self invoking functions are anonymous functions which do not need to be called to return a value.
```js
(function(n) {
console.log(n * n)
})(2) // 4, but instead of just printing if we want to return and store the data, we do as shown below
let squaredNum = (function(n) {
return n * n
})(10)
console.log(squaredNum)
```
### Arrow Function
Arrow function is an alternative to write a function, however function declaration and arrow function have some minor differences.
Arrow function uses arrow instead of the keyword function to declare a function. Let us see both function declaration and arrow function.
```js
// This is how we write normal or declaration function
// Let us change this declaration function to an arrow function
function square(n) {
return n * n
}
console.log(square(2)) // 4
const square = n => {
return n * n
}
console.log(square(2)) // -> 4
// if we have only one line, it can be written as follows, explicit return
const square = n => n * n // -> 4
```
```js
const changeToUpperCase = arr => {
const newArr = []
for (const element of arr) {
newArr.push(element.toUpperCase())
}
return newArr
}
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
console.log(changeToUpperCase(countries))
// ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
```
```js
const printFullName = (firstName, lastName) => {
return `${firstName} ${lastName}`
}
console.log(printFullName('Asabeneh', 'Yetayeh'))
```
The above function has only the return statement, therefore, we can explicitly return it as follows.
```js
const printFullName = (firstName, lastName) => `${firstName} ${lastName}`
console.log(printFullName('Asabeneh', 'Yetayeh'))
```
### Function with default parameters
Sometimes we pass default values to parameters, when we invoke the function if we do not pass an argument the default value will be used. Both function declaration and arrow function can have a default value or values.
```js
// syntax
// Declaring a function
function functionName(param = value) {
//codes
}
// Calling function
functionName()
functionName(arg)
```
**Example:**
```js
function greetings(name = 'Peter') {
let message = `${name}, welcome to 30 Days Of JavaScript!`
return message
}
console.log(greetings())
console.log(greetings('Asabeneh'))
```
```js
function generateFullName(firstName = 'Asabeneh', lastName = 'Yetayeh') {
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(generateFullName())
console.log(generateFullName('David', 'Smith'))
```
```js
function calculateAge(birthYear, currentYear = 2019) {
let age = currentYear - birthYear
return age
}
console.log('Age: ', calculateAge(1819))
```
```js
function weightOfObject(mass, gravity = 9.81) {
let weight = mass * gravity + ' N' // the value has to be changed to string first
return weight
}
console.log('Weight of an object in Newton: ', weightOfObject(100)) // 9.81 gravity at the surface of Earth
console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gravity at surface of Moon
```
Let us see how we write the above functions with arrow functions
```js
// syntax
// Declaring a function
const functionName = (param = value) => {
//codes
}
// Calling function
functionName()
functionName(arg)
```
**Example:**
```js
const greetings = (name = 'Peter') => {
let message = name + ', welcome to 30 Days Of JavaScript!'
return message
}
console.log(greetings())
console.log(greetings('Asabeneh'))
```
```js
const generateFullName = (firstName = 'Asabeneh', lastName = 'Yetayeh') => {
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(generateFullName())
console.log(generateFullName('David', 'Smith'))
```
```js
const calculateAge = (birthYear, currentYear = 2019) => currentYear - birthYear
console.log('Age: ', calculateAge(1819))
```
```js
const weightOfObject = (mass, gravity = 9.81) => mass * gravity + ' N'
console.log('Weight of an object in Newton: ', weightOfObject(100)) // 9.81 gravity at the surface of Earth
console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gravity at surface of Moon
```
### Function declaration versus Arrow function
🌕 You are a rising star, now you knew function . Now, you are super charged with the power of functions. You have just completed day 7 challenges and you are 7 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises
1. Declare a function _fullName_ and it print out your full name.
2. Declare a function _fullName_ and now it takes firstName, lastName as a parameter and it returns your full - name.
3. Declare a function _addNumbers_ and it takes two two parameters and it returns sum.
4. An area of a rectangle is calculated as follows: _area = length x width_. Write a function which calculates _areaOfRectangle_.
5. A perimeter of a rectangle is calculated as follows: _perimeter= 2x(length + width)_. Write a function which calculates _perimeterOfRectangle_.
6. A volume of a rectangular prism is calculated as follows: _volume = length x width x height_. Write a function which calculates _volumeOfRectPrism_.
7. Area of a circle is calculated as follows: _area = π x r x r_. Write a function which calculates _areaOfCircle_
8. Circumference of a circle is calculated as follows: _circumference = 2πr_. Write a function which calculates _circumOfCircle_
9. Density of a substance is calculated as follows:_density= mass/volume_. Write a function which calculates _density_.
10. Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, _speed_.
11. Weight of a substance is calculated as follows: _weight = mass x gravity_. Write a function which calculates _weight_.
12. Temperature in oC can be converted to oF using this formula: _oF = (oC x 9/5) + 32_. Write a function which convert oC to oF _convertCelciusToFahrenheit_.
13. Body mass index(BMI) is calculated as follows: _bmi = weight in Kg / (height x height) in m2_. Write a function which calculates _bmi_. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is _underweight, normal, overweight_ or _obese_ based the information given below.
- The same groups apply to both men and women.
- _Underweight_: BMI is less than 18.5
- _Normal weight_: BMI is 18.5 to 24.9
- _Overweight_: BMI is 25 to 29.9
- _Obese_: BMI is 30 or more
14. Write a function called _checkSeason_, it takes a month parameter and returns the season:Autumn, Winter, Spring or Summer.
15. Math.max returns its largest argument. Write a function findMax that takes three arguments and returns their maximum with out using Math.max method.
```js
console.log(findMax(0, 10, 5))
10
console.log(findMax(0, -10, -2))
0
```
16. Linear equation is calculated as follows: _ax + by + c = 0_. Write a function which calculates value of a linear equation, _solveLinEquation_.
17. Quadratic equation is calculated as follows: _ax2 + bx + c = 0_. Write a function which calculates value or values of a quadratic equation, _solveQuadEquation_.
```js
console.log(solveQuadratic()) // {0}
console.log(solveQuadratic(1, 4, 4)) // {-2}
console.log(solveQuadratic(1, -1, -2)) // {2, -1}
console.log(solveQuadratic(1, 7, 12)) // {-3, -4}
console.log(solveQuadratic(1, 0, -4)) //{2, -2}
console.log(solveQuadratic(1, -1, 0)) //{1, 0}
```
18. Declare a function name _printArray_. It takes array as a parameter and it prints out each value of the array.
19. 11. Write a function name _showDateTime_ which shows time in this format: 08/01/2020 04:08 using the Date object.
```sh
showDateTime()
08/01/2020 04:08
```
20. Declare a function name _swapValues_. This function swaps value of x to y.
```js
swapValues(3, 4) // x => 4, y=>3
swapValues(4, 5) // x = 5, y = 4
```
21. Declare a function name _reverseArray_. It takes array as a parameter and it returns the reverse of the array (don't use method).
```js
console.log(reverseArray([1, 2, 3, 4, 5]))
//[5, 4, 3, 2, 1]
console.log(reverseArray(['A', 'B', 'C']))
//['C', 'B', 'A']
```
22. Declare a function name _capitalizeArray_. It takes array as a parameter and it returns the - capitalizedarray.
23. Declare a function name _addItem_. It takes an item parameter and it returns an array after adding the item
24. Declare a function name _removeItem_. It takes an index parameter and it returns an array after removing an item
25. Declare a function name _sumOfNumbers_. It takes a number parameter and it adds all the numbers in that range.
26. Declare a function name _sumOfOdds_. It takes a number parameter and it adds all the odd numbers in that - range.
27. Declare a function name _sumOfEven_. It takes a number parameter and it adds all the even numbers in that - range.
28. Declare a function name evensAndOdds . It takes a positive integer as parameter and it counts number of evens and odds in the number.
```sh
evensAndOdds(100);
The number of odds are 50.
The number of evens are 51.
```
29. Write a function which takes any number of arguments and return the sum of the arguments
```js
sum(1, 2, 3) // -> 6
sum(1, 2, 3, 4) // -> 10
```
30. Writ a function which generates a _randomUserIp_.
31. Write a function which generates a _randomMacAddress_
32. Declare a function name _randomHexaNumberGenerator_. When this function is called it generates a random hexadecimal number. The function return the hexadecimal number.
```sh
console.log(randomHexaNumberGenerator());
'#ee33df'
```
33. Declare a function name _userIdGenerator_. When this function is called it generates seven character id. The function return the id.
```sh
console.log(userIdGenerator());
41XTDbE
```
34. Modify question number n . Declare a function name _userIdGeneratedByUser_. It doesnt take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated.
```sh
userIdGeneratedByUser()
'kcsy2
SMFYb
bWmeq
ZXOYh
2Rgxf
'
userIdGeneratedByUser()
'1GCSgPLMaBAVQZ26
YD7eFwNQKNs7qXaT
ycArC5yrRupyG00S
UbGxOFI7UXSWAyKN
dIV0SSUTgAdKwStr
'
```
35. Write a function name _rgbColorGenerator_ and it generates rgb colors.
```sh
rgbColorGenerator()
rgb(125,244,255)
```
36. Write a function **_arrayOfHexaColors_** which return any number of hexadecimal colors in an array.
37. Write a function **_arrayOfRgbColors_** which return any number of RGB colors in an array.
38. Write a function **_convertHexaToRgb_** which converts hexa color to rgb and it returns an rgb color.
39. Write a function **_convertRgbToHexa_** which converts rgb to hexa color and it returns an hexa color.
40. Write a function **_generateColors_** which can generate any number of hexa or rgb colors.
```js
console.log(generateColors('hexa', 3)) // ['#a3e12f', '#03ed55', '#eb3d2b']
console.log(generateColors('hexa', 1)) // '#b334ef'
console.log(generateColors('rgb', 3)) // ['rgb(5, 55, 175)', 'rgb(50, 105, 100)', 'rgb(15, 26, 80)']
console.log(generateColors('rgb', 1)) // 'rgb(33,79, 176)'
```
41. Call your function _shuffleArray_, it takes an array as a parameter and it returns a shuffled array
42. Call your function _factorial_, it takes a whole number as a parameter and it return a factorial of the number
43. Call your function _isEmpty_, it takes a parameter and it checks if it is empty or not
44. Call your function _sum_, it takes any number of arguments and it returns the sum.
45. Write a function called _sumOfArrayItems_, it takes an array parameter and return the sum of all the items. Check if all the array items are number types. If not give return reasonable feedback.
46. Write a function called _average_, it takes an array parameter and returns the average of the items. Check if all the array items are number types. If not give return reasonable feedback.
47. Write a function called _modifyArray_ takes array as parameter and modifies the fifth item of the array and return the array. If the array length is less than five it return 'item not found'.
```js
console.log(modifyArray(['Avocado', 'Tomato', 'Potato','Mango', 'Lemon','Carrot']);
// →['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon','Microsoft', 'IBM']);
// →['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM']
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon']);
// →'Not Found'
```
48. Write a function called _isPrime_, which checks if a number is prime number.
49. Write a functions which checks if all items are unique in the array.
50. Write a function which checks if all the items of the array are the same data type.
51. JavaScript variable name does not support special characters or symbols except \$ or \_. Write a function **\*isValidVariable** which check if a variable is valid or invalid variable.
52. Write a function which returns array of seven random numbers in a range of 0-9. All the numbers must be unique.
```js
sevenRandomNumbers()[(1, 4, 5, 7, 9, 8, 0)]
```
53. Write a function called reverseCountries, it takes countries array and first it copy the array and returns the reverse of the original array
🎉 CONGRATULATIONS ! 🎉
[<< Day 6](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/06_Day/06_day_loops.md) | [Day 8 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/08_Day/08_day_objects.md)

@ -0,0 +1,195 @@
const countries = [
'Afghanistan',
'Albania',
'Algeria',
'Andorra',
'Angola',
'Antigua and Barbuda',
'Argentina',
'Armenia',
'Australia',
'Austria',
'Azerbaijan',
'Bahamas',
'Bahrain',
'Bangladesh',
'Barbados',
'Belarus',
'Belgium',
'Belize',
'Benin',
'Bhutan',
'Bolivia',
'Bosnia and Herzegovina',
'Botswana',
'Brazil',
'Brunei',
'Bulgaria',
'Burkina Faso',
'Burundi',
'Cambodia',
'Cameroon',
'Canada',
'Cape Verde',
'Central African Republic',
'Chad',
'Chile',
'China',
'Colombi',
'Comoros',
'Congo (Brazzaville)',
'Congo',
'Costa Rica',
"Cote d'Ivoire",
'Croatia',
'Cuba',
'Cyprus',
'Czech Republic',
'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic',
'East Timor (Timor Timur)',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Fiji',
'Finland',
'France',
'Gabon',
'Gambia, The',
'Georgia',
'Germany',
'Ghana',
'Greece',
'Grenada',
'Guatemala',
'Guinea',
'Guinea-Bissau',
'Guyana',
'Haiti',
'Honduras',
'Hungary',
'Iceland',
'India',
'Indonesia',
'Iran',
'Iraq',
'Ireland',
'Israel',
'Italy',
'Jamaica',
'Japan',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Korea, North',
'Korea, South',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Macedonia',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Mauritania',
'Mauritius',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepal',
'Netherlands',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Panama',
'Papua New Guinea',
'Paraguay',
'Peru',
'Philippines',
'Poland',
'Portugal',
'Qatar',
'Romania',
'Russia',
'Rwanda',
'Saint Kitts and Nevis',
'Saint Lucia',
'Saint Vincent',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Serbia and Montenegro',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'Spain',
'Sri Lanka',
'Sudan',
'Suriname',
'Swaziland',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Togo',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Vatican City',
'Venezuela',
'Vietnam',
'Yemen',
'Zambia',
'Zimbabwe'
]

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:07 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:07 Day</h1>
<h2>Functions</h2>
<script src="./data/countries.js"></script>
<script src="./scripts/main.js"></script>
</body>
</html>

@ -0,0 +1,2 @@
console.log(countries)
alert('Open the console and check if the countries has been loaded')

@ -0,0 +1,493 @@
<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 7](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/07_Day/07_day_functions.md) | [Day 9 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md)
![Thirty Days Of JavaScript](../images/banners/day_1_8.png)
- [📔 Day 8](#%f0%9f%93%94-day-8)
- [Scope](#scope)
- [Window Scope](#window-scope)
- [Global scope](#global-scope)
- [Local scope](#local-scope)
- [📔 Object](#%f0%9f%93%94-object)
- [Creating an empty object](#creating-an-empty-object)
- [Creating an objecting with values](#creating-an-objecting-with-values)
- [Getting values from an object](#getting-values-from-an-object)
- [Creating object methods](#creating-object-methods)
- [Setting new key for an object](#setting-new-key-for-an-object)
- [Object Methods](#object-methods)
- [Getting object keys using Object.keys()](#getting-object-keys-using-objectkeys)
- [Getting object values using Object.values()](#getting-object-values-using-objectvalues)
- [Getting object keys and values using Object.entries()](#getting-object-keys-and-values-using-objectentries)
- [Checking properties using hasOwnProperty()](#checking-properties-using-hasownproperty)
- [💻 Exercises](#%f0%9f%92%bb-exercises)
# 📔 Day 8
## Scope
Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word _var_, _let_ and _const_. A variable can declared at different scope. In this section we will see the scope, scope of variables when we use var or let.
Variables scopes can be:
- Window
- Global
- Local
Variable can be declared globally or locally or window scope. We will see both global and local scope.
Anything declared without let, var or const is scoped at window level.
Let us image we have a scope.js file.
### Window Scope
Without using console.log() open your browser and check, you will see the value of a and b if you write a or b on the browser. That means a and b are already available in the window.
```js
//scope.js
a = 'JavaScript' // is a window scope this found anywhere
b = 10 // this is a window scope variable
function letsLearnScope() {
console.log(a, b)
if (true) {
console.log(a, b)
}
}
console.log(a, b) // accessible
```
### Global scope
A globally declared variable can be access every where in the same file. But the term global is relative. It can be global to the file or it can be global relative to some block of codes.
```js
//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
if (true) {
let a = 'Python'
let b = 100
console.log(a, b) // Python 100
}
console.log(a, b)
}
letsLearnScope()
console.log(a, b) // JavaScript 10, accessible
```
### Local scope
A local declared variable can be access only certain block code.
```js
//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
let c = 30
if (true) {
// we can access from the function and outside the function but
// variables declared inside the if will not be accessed outside the if block
let a = 'Python'
let b = 20
let d = 40
console.log(a, b, c) // Python 20 30
}
// we can not access c because c's scope is only the if block
console.log(a, b) // JavaScript 10
}
letsLearnScope()
console.log(a, b) // JavaScript 10, accessible
```
Now, you have an understanding of scope. A variable declared with *var* only scoped to function but variable declared with *let* or *const* is block scope(function block, if block, loop etc)
```js
//scope.js
function letsLearnScope() {
var gravity = 9.81
console.log(gravity)
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
if (true){
var gravity = 9.81
console.log(gravity) // 9.81
}
console.log(gravity) // 9.81
for(var i = 0; i < 3; i++){
console.log(i) // 1, 2, 3
}
console.log(i)
```
In ES6 and above there is *let* and *const*, so you will suffer from the sneakiness of *var*. When we use *let* our variable is block scope and it will not infect other parts of our code.
```js
//scope.js
function letsLearnScope() {
// you can use let or const, but gravity is constant I prefer to use const
const gravity = 9.81
console.log(gravity)
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
if (true){
const gravity = 9.81
console.log(gravity) // 9.81
}
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
for(let i = 0; i < 3; i++){
console.log(i) // 1, 2, 3
}
// console.log(i), Uncaught ReferenceError: gravity is not defined
```
The scope *let* and *const* is the same. The difference is only reassigning. We can not change or reassign the value of const variable. I would strongly suggest you to use *let* and *const*, by using *let* and *const* you will writ clean code and avoid hard to debug mistakes. As a rule of thumb, you can use *let* for any value which change, *const* for any constant value, array, object, arrow function and function expression.
## 📔 Object
Everything can be an object and objects do have properties and properties have values, so an object is key value pair. The order of the key is not reserved, or there is no order.
Creating an object literal. To create an object literal, we use two curly brackets.
### Creating an empty object
An empty object
```js
const person = {}
```
### Creating an objecting with values
Now, the person object has firstName, lastName, age, location, skills and isMarried properties. The value of properties or keys could be a string, number, boolean, an object, null, undefined or a function.
Let us see some examples of object. Each key has a value in object.
```js
const rectangle = {
length: 20,
width: 20
}
console.log(rectangle) // {length: 20, width: 20}
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js'
],
isMarried: true
}
console.log(person)
```
### Getting values from an object
We can access values of object using two methods:
- using . followed by key name if the key-name is a one word
- using square bracket and a quote
```js
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js'
],
getFullName: function() {
return `${this.firstName}${this.lastName}`
},
'phone number': '+3584545454545'
}
// accessing values using .
console.log(person.firstName)
console.log(person.lastName)
console.log(person.age)
console.log(person.location)
// value can be accessed using square bracket and key name
console.log(person['firstName'])
console.log(person['lastName'])
console.log(person['age'])
console.log(person['age'])
console.log(person['location'])
// for instance to access the phone number we only use the square bracket method
console.log(person['phone number'])
```
### Creating object methods
Now, the person object has getFullName properties. The getFullName is function inside the person object and we call it an object method. The _this_ key word refers to the object itself. We can use the word _this_ to access the values of different properties of the object. We can not use an arrow function as object method because the word this refers to the window inside an arrow function instead of the object itself. Example of object:
```js
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js'
],
getFullName: function() {
return `${this.firstName} ${this.lastName}`
}
}
console.log(person.getFullName())
// Asabeneh Yetayeh
```
### Setting new key for an object
An object is a mutable data structure and we can modify the content of an object after it gets created.
Setting a new keys in an object
```js
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
city: 'Helsinki',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Node',
'MongoDB',
'Python',
'D3.js'
],
getFullName: function() {
return `${this.firstName} ${this.lastName}`
}
}
person.nationality = 'Ethiopian'
person.country = 'Finland'
person.title = 'teacher'
person.skills.push('Meteor')
person.skills.push('SasS')
person.isMarried = true
person.getPersonInfo = function() {
let skillsWithoutLastSkill = this.skills
.splice(0, this.skills.length - 1)
.join(', ')
let lastSkill = this.skills.splice(this.skills.length - 1)[0]
let skills = `${skillsWithoutLastSkill}, and ${lastSkill}`
let fullName = this.getFullName()
let statement = `${fullName} is a ${this.title}.\nHe lives in ${this.country}.\nHe teaches ${skills}.`
return statement
}
console.log(person)
console.log(person.getPersonInfo())
```
```sh
Asabeneh Yetayeh is a teacher.
He lives in Finland.
He teaches HTML, CSS, JavaScript, React, Node, MongoDB, Python, D3.js, Meteor, and SasS.
```
### Object Methods
There are different methods to manipulate an object. Let us see some of the available methods.
_Object.assign_: To copy an object without modifying the original object
```js
const person = {
firstName: 'Asabeneh',
age: 250,
country: 'Finland',
city:'Helsinki',
skills: ['HTML', 'CSS', 'JS'],
title: 'teacher',
address: {
street: 'Heitamienkatu 16',
pobox: 2002,
city: 'Helsinki'
},
getPersonInfo: function() {
return `I am ${this.firstName} and I live in ${city}, ${this.country}. I am ${this.age}.`
}
}
//Object methods: Object.assign, Object.keys, Object.values, Object.entries
//hasOwnProperty
const copyPerson = Object.assign({}, person)
console.log(copyPerson)
```
#### Getting object keys using Object.keys()
_Object.keys_: To get the keys or properties of an object as an array
```js
const keys = Object.keys(copyPerson)
console.log(keys) //['name', 'age', 'country', 'skills', 'address', 'getPersonInfo']
const address = Object.keys(copyPerson.address)
console.log(address) //['street', 'pobox', 'city']
```
#### Getting object values using Object.values()
_Object.values_:To get values of an object as an array
```js
const values = Object.values(copyPerson)
console.log(values)
```
#### Getting object keys and values using Object.entries()
_Object.entries_:To get the keys and values in an array
```js
const entries = Object.entries(copyPerson)
console.log(entries)
```
#### Checking properties using hasOwnProperty()
_hasOwnProperty_: To check if a specific key or property exist in an object
```js
console.log(copyPerson.hasOwnProperty('name'))
console.log(copyPerson.hasOwnProperty('score'))
```
🌕 You are astonishing. Now, you are super charged with the power of objects. You have just completed day 7 challenges and you are 7 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises
1. Create an empty object called dog
1. Print the the dog object on the console
1. Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return _woof woof_
1. Get name, legs, color, age and bark value from the dog object
1. Set new properties the dog object: breed, getDogInfo
1. Create an object literal called _personAccount_. It has _firstName, lastName, incomes, expenses_ properties and it has _totalIncome, totalExpense, accountInfo,addIncome, addExpense_ and _accountBalance_ methods. Incomes is a set of incomes and its description and expenses is a set of incomes and its description.
1. Count logged in users,count users having greater than equal to 50 points from the following object.
````js
const users = {
Alex: {
email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 20,
isLoggedIn: false,
points: 30
},
Asab: {
email: 'asab@asab.com',
skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
age: 25,
isLoggedIn: false,
points: 50
},
Brook: {
email: 'daniel@daniel.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
age: 30,
isLoggedIn: true,
points: 50
},
Daniel: {
email: 'daniel@alex.com',
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
age: 20,
isLoggedIn: false,
points: 40
},
John: {
email: 'john@john.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
age: 20,
isLoggedIn: true,
points: 50
},
Thomas: {
email: 'thomas@thomas.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
age: 20,
isLoggedIn: false,
points: 40
},
Paul: {
email: 'paul@paul.com',
skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
age: 20,
isLoggedIn: false,
points: 40
}
}```
````
1. Find people who are MERN stack developer from the users object
1. Set your name in the users object without modifying the original users object
1. Get all keys or properties of users object
1. Get all the values of users object
1. Use the countries object to print a country name, capital, populations and languages.
🎉 CONGRATULATIONS ! 🎉
[<< Day 7](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/07_Day/07_day_functions.md) | [Day 9 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:08 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:08 Day</h1>
<h2>Objects</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>
</html>

@ -0,0 +1,2 @@
console.log(countries)
alert('Open the console and check if the countries has been loaded')

@ -0,0 +1,694 @@
<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 8](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/08_Day/08_day_objects.md) | [Day 10 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/10_Day/10_day_Set_and_Map.md)
![Day 5](../images/banners/day_1_9.png)
- [Day 9](#day-9)
- [Higher Order Function](#higher-order-function)
- [Callback](#callback)
- [Returning function](#returning-function)
- [setting time](#setting-time)
- [setInterval](#setinterval)
- [setTimeout](#settimeout)
- [Functional Programming](#functional-programming)
- [forEach](#foreach)
- [map](#map)
- [filter](#filter)
- [reduce](#reduce)
- [every](#every)
- [find](#find)
- [findIndex](#findindex)
- [some](#some)
- [sort](#sort)
- [Sorting string values](#sorting-string-values)
- [Sorting Numeric values](#sorting-numeric-values)
- [Sorting Object Arrays](#sorting-object-arrays)
- [💻 Exercises](#%f0%9f%92%bb-exercises)
# Day 9
## Higher Order Function
Higher order functions are functions which take other function as a parameter or return a function as a value. The function passed as a parameter is called callback.
### Callback
A callback is a function which can be passed as parameter to other function. See the example below.
```js
// a callback function, the function could be any name
const callback = (n) => {
return n ** 2
}
// function take other function as a callback
function cube(callback, n) {
return callback(n) * n
}
console.log(cube(callback, 3))
```
### Returning function
Higher order functions return function as a value
```js
// Higher order function returning an other function
const higherOrder = n => {
const doSomething = m => {
const doWhatEver = t => {
return 2 * n + 3 * m + t
}
return doWhatEver
}
return doSomething
}
console.log(higherOrder(2)(3)(10))
```
Let us see were we use call back functions.For instance the _forEach_ method uses call back.
```js
const numbers = [1, 2, 3, 4]
const sumArray = arr => {
let sum = 0
const callBack = function(element) {
sum += element
}
numbers.forEach(callback)
return sum
}
console.log(sumArray(numbers))
```
```sh
15
```
The above example can be simplified as follows:
```js
const numbers = [1, 2, 3, 4]
const sumArray = arr => {
let sum = 0
numbers.forEach(function(element) {
sum += element
})
return sum
}
console.log(sumArray(numbers))
```
```sh
15
```
### setting time
In JavaScript we can execute some activity on certain interval of time or we can schedule(wait) for sometime to execute some activities.
- setInterval
- setTimeout
#### setInterval
In JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. The setInterval global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback will be always called in that interval of time.
```js
// syntax
function callBack() {
// code goes here
}
setInterval(callback, duration)
```
```js
function sayHello() {
console.log('Hello')
}
setInterval(sayHello, 2000) // it prints hello in every 2 seconds
```
#### setTimeout
In JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time.
```js
// syntax
function callback() {
// code goes here
}
setTimeout(callback, duration) // duration in milliseconds
```
```js
function sayHello() {
console.log('Hello')
}
setTimeout(sayHello, 2000) // it prints hello after it waits for 2 seconds.
```
## Functional Programming
Instead of writing regular loop, latest version of JavaScript introduced lots of built in methods which can help us to solve complicated problems. All builtin methods take callback function. In this section, we will see _forEach_, _map_, _filter_, _reduce_, _find_, _every_, _some_, and _sort_.
### forEach
_forEach_: Iterate an array elements. We use _forEach_ only with arrays. It takes a callback function with elements, index parameter and array itself. The index and the array optional.
```js
arr.forEach(function(element, index, arr) {
console.log(index, element, arr)
})
// The above code can be written using arrow function
arr.forEach((element, index, arr) => {
console.log(index, element, arr)
})
// The above code can be written using arrow function and explicit return
arr.forEach((element, index, arr) => console.log(index, element, arr))
```
```js
let sum = 0;
const numbers = [1,2,3,4,5];
numbers.forEach(num => console.log(num)))
console.log(sum)
```
```sh
1
2
3
4
5
```
```js
let sum = 0;
const numbers = [1,2,3,4,5];
numbers.forEach(num => sum += num))
console.log(sum)
```
```sh
15
```
```js
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland']
countries.forEach(element => console.log(element.toUpperCase()))
```
```sh
FINLAND
DENMARK
SWEDEN
NORWAY
ICELAND
```
### map
_map_: Iterate an array elements and modify the array elements. It takes a callback function with elements and index parameter and return a new array.
```js
const modifiedArray = arr.map(function(element, index) {
return element
})
```
```js
/*Arrow function and explicit return
const modifiedArray = arr.map((element,index) => element);
*/
//Example
const numbers = [1, 2, 3, 4, 5]
const numbersSquare = numbers.map(num => num * num)
console.log(numbersSquare)
```
```sh
[1, 4, 9, 16, 25]
```
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const namesToUpperCase = names.map(name => name.toUpperCase())
console.log(namesToUpperCase)
```
```sh
['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK']
```
```js
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya'
]
const countriesToUpperCase = countries.map(country => country.toUpperCase())
console.log(countriesToUpperCase)
/*
// Arrow function
const countriesToUpperCase = countries.map((country) => {
return country.toUpperCase();
})
//Explicit return arrow function
const countriesToUpperCase = countries.map(country => country.toUpperCase());
*/
```
```sh
['ALBANIA', 'BOLIVIA', 'CANADA', 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY', 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA']
```
```js
const countriesFirstThreeLetters = countries.map(country =>
country.toUpperCase().slice(0, 3)
)
```
```sh
 ["ALB", "BOL", "CAN", "DEN", "ETH", "FIN", "GER", "HUN", "IRE", "JAP", "KEN"]
```
### filter
_Filter_: Filter out items which full fill filtering conditions and return a new array.
```js
//Filter countries containing land
const countriesContainingLand = countries.filter(country =>
country.includes('land')
)
console.log(countriesContainingLand)
```
```sh
['Finland', 'Ireland']
```
```js
const countriesEndsByia = countries.filter(country => country.includes('ia'))
console.log(countriesEndsByia)
```
```sh
['Albania', 'Bolivia','Ethiopia']
```
```js
const countriesHaveFiveLetters = countries.filter(
country => country.length === 5
)
console.log(countriesHaveFiveLetters)
```
```sh
['Japan', 'Kenya']
```
```js
const scores = [
{ name: 'Asabeneh', score: 95 },
{ name: 'Mathias', score: 80 },
{ name: 'Elias', score: 50 },
{ name: 'Martha', score: 85 },
{ name: 'John', score: 100 }
]
const scoresGreaterEight = scores.filter(score => score.score > 80)
console.log(scoresGreaterEight)
```
```sh
[{name: 'Asabeneh', score: 95}, {name: 'Martha', score: 85},{name: 'John', score: 100}]
```
### reduce
_reduce_: Reduce takes a callback function. The call back function takes accumulator and current value as a parameter and returns a single value:
```js
const numbers = [1, 2, 3, 4, 5]
const sum = numbers.reduce((accum, curr) => accum + curr)
console.log(sum)
```
```js
15
```
### every
_every_: Check if all the elements are similar in one aspect. It returns boolean
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const areAllStr = names.every(name => typeof name === 'string')
console.log(arrAllStr)
```
```sh
true
```
```js
const bools = [true, true, true, true]
const areAllTrue = bools.every(b => {
return b === true
})
console.log(areAllTrue) //true
```
```sh
true
```
### find
_find_: Return the first element which satisfies the condition
```js
const ages = [24, 22, 25, 32, 35, 18]
const age = ages.find(age => age < 20)
console.log(age)
```
```js
18
```
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const result = names.find(name => name.length > 7)
console.log(result)
```
```sh
Asabeneh
```
```js
const scores = [
{ name: 'Asabeneh', score: 95 },
{ name: 'Mathias', score: 80 },
{ name: 'Elias', score: 50 },
{ name: 'Martha', score: 85 },
{ name: 'John', score: 100 }
]
const score = scores.find(user => {
return user.score > 80
})
console.log(score)
```
```sh
{ name: "Asabeneh", score: 95 }
```
### findIndex
_findIndex_: Return the position of the first element which satisfies the condition
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const ages = [24, 22, 25, 32, 35, 18]
const result = names.findIndex(name => name.length > 7)
console.log(result) // 0
const age = ages.findIndex(age => age < 20)
console.log(age) // 5
```
### some
_some_: Check if some of the elements are similar in one aspect. It returns boolean
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const bools = [true, true, true, true]
const areSomeTrue = bools.some(b => {
return b === true
})
console.log(areSomeTrue) //true
```
```js
const areAllStr = names.some(name => typeof name === 'number')
console.log(areAllStr) // false
```
### sort
_sort_: The sort methods arranges the array elements either ascending or descending order. By default, the **_sort()_** method sorts values as strings.This works well for string array items but not for numbers. If number values are sorted as strings and it give us wrong result. Sort method modify the original array. It is recommended to copy the original data before you start using _sort_ method.
#### Sorting string values
```js
const products = ['Milk', 'Coffee', 'Sugar', 'Honey', 'Apple', 'Carrot']
console.log(products.sort()) // ['Apple', 'Carrot', 'Coffee', 'Honey', 'Milk', 'Sugar']
//Now the original products array is also sorted
```
#### Sorting Numeric values
As you can see in the example below, 100 came first after sorted in ascending order. Sort converts items to string , since '100' and other numbers compared, 1 which the beginning of the string '100' became the smallest. To avoid this, we use a compare call back function inside the sort method, which return a negative, zero or positive.
```js
const numbers = [9.81, 3.14, 100, 37]
// Using sort method to sort number items provide a wrong result. see below
console.log(numbers.sort()) //[100, 3.14, 37, 9.81]
numbers.sort(function(a, b) {
return a - b
})
console.log(numbers) // [3.14, 9.81, 37, 100]
numbers.sort(function(a, b) {
return b - a
})
console.log(numbers) //[100, 37, 9.81, 3.14]
```
#### Sorting Object Arrays
When ever we sort objects in an array. We use the object key to compare. Lets see the example below.
```js
objArr.sort(function(a, b) {
if (a.key < b.key) return -1
if (a.key > b.key) return 1
return 0
})
// or
objArr.sort(function(a, b) {
if (a['key'] < b['key']) return -1
if (a['key'] > b['key']) return 1
return 0
})
const users = [
{ name: 'Asabeneh', age: 150 },
{ name: 'Brook', age: 50 },
{ name: 'Eyo', age: 100 },
{ name: 'Elias', age: 22 }
]
users.sort((a, b) => {
if (a.age < b.age) return -1
if (a.age > b.age) return 1
return 0
})
console.log(users) // sorted ascending
//[{…}, {…}, {…}, {…}]
```
🌕 You are doing great.Never give up because great things take time. You have just completed day 9 challenges and you are 9 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises
```js
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const products = [
{ product: 'banana', price: 3 },
{ product: 'mango', price: 6 },
{ product: 'potato', price: ' ' },
{ product: 'avocado', price: 8 },
{ product: 'coffee', price: 10 },
{ product: 'tea', price: '' }
]
```
1. Explain the difference between **_forEach, map, filter, and reduce_**.
2. Define a call function before you them in forEach, map, filter or reduce.
3. Use **_forEach_** to console.log each country in the countries array.
4. Use **_forEach_** to console.log each name in the names array.
5. Use **_forEach_** to console.log each number in the numbers array.
6. Use **_map_** to create a new array by changing each country to uppercase in the countries array.
7. Use **_map_** to create an array of countries length from countries array.
8. Use **_map_** to create a new array by changing each number to square in the numbers array
9. Use **_map_** to change to each name to uppercase in the names array
10. Use **_map_** to map the products array to its corresponding prices.
11. Use **_filter_** to filter out countries containing **_land_**.
12. Use **_filter_** to filter out countries having six character.
13. Use **_filter_** to filter out countries containing six letters and more in the country array.
14. Use **_filter_** to filter out country start with 'E';
15. Use **_filter_** to filter out only prices with values.
16. Find the total price of products by chaining two or more array iterators(eg. arr.map(callback).filter(callback).reduce(callback))
17. Find the sum of price of products using only reduce reduce(callback))
18. Declare a function called getStringLists which takes an array as a parameter and then returns an array only with string items.
19. Use **_reduce_** to sum all the numbers in the numbers array.
20. Use **_reduce_** to concatenate all the countries and to produce this sentence: **_Estonia, Finland, Sweden, Denmark, Norway, and IceLand are north European countries_**
21. Explain the difference between **_some_** and **_every_**
22. Use **_some_** to check if some names' length greater than seven in names array
23. Use **_every_** to check if all the countries contain the word land
24. Explain the difference between **_find_** and **_findIndex_**.
25. Use **_find_** to find the first country containing only six letters in the countries array
26. Use **_findIndex_** to find the position of the first country containing only six letters in the countries array
27. Use **_findIndex_** to find the position of **_Norway_** if it doesn't exist in the array you will get -1.
28. Use **_findIndex_** to find the position of **_Russia_** if it doesn't exist in the array you will get -1.
29. Declare a function called **_categorizeCountries_** which returns an array of countries which have some common pattern(you find the countries array in this repository as countries.js(eg 'land', 'ia', 'island','stan')).
30. Create a function which return an array of objects, which is the letter and the number of times the letter use to start with a name of a country.
31. Declare a **_getFirstTenCountries_** function and return an array of ten countries. Use different functional programming to work on the countries.js array
32. Declare a **_getLastTenCountries_** function which which returns the last ten countries in the countries array.
33. Find out which _letter_ is used many _times_ as initial for a country name from the countries array (eg. Finland, Fiji, France etc)
34. Use the countries information, in the data folder. Sort countries by name, by capital, by population
35. \*\*\* Find the 10 most spoken languages:
````js
// Your output should look like this
console.log(mostSpokenLanguages(countries, 10))
[(91, 'English'),
(45, 'French'),
(25, 'Arabic'),
(24, 'Spanish'),
(9, 'Russian'),
(9, 'Portuguese'),
(8, 'Dutch'),
(7, 'German'),
(5, 'Chinese'),
(4, 'Swahili'),
(4, 'Serbian')]
// Your output should look like this
console.log(mostSpokenLanguages(countries, 3))
[
(91, 'English'),
(45, 'French'),
(25, 'Arabic')
]```
````
36. \*\*\* Use countries_data.js file create a function which create the ten most populated countries
````js
console.log(mostPopulatedCountries(countries, 10))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000},
{country: 'Indonesia', population: 258705000},
{country: 'Brazil', population: 206135893},
{country: 'Pakistan', population: 194125062},
{country: 'Nigeria', population: 186988000},
{country: 'Bangladesh', population: 161006790},
{country: 'Russian Federation', population: 146599183},
{country: 'Japan', population: 126960000}
]
console.log(mostPopulatedCountries(countries, 3))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000}
]```
````
37. \*\*\* Try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create an object called statistics and create all the functions which do statistical calculations as method for the statistics object. Check the output below.
```js
const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
console.log('Count:', statistics.count()) // 25
console.log('Sum: ', statistics.sum()) // 744
console.log('Min: ', statistics.min()) // 24
console.log('Max: ', statistics.max()) // 38
console.log('Range: ', statistics.range() // 14
console.log('Mean: ', statistics.mean()) // 30
console.log('Median: ',statistics.median()) // 29
console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5}
console.log('Variance: ',statistics.var()) // 17.5
console.log('Standard Deviation: ', statistics.std()) // 4.2
console.log('Variance: ',statistics.var()) // 17.5
console.log('Frequency Distribution: ',statistics.freqDist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
```sh
console.log(statistics.describe())
Count: 25
Sum: 744
Min: 24
Max: 38
Range: 14
Mean: 30
Median: 29
Mode: (26, 5)
Variance: 17.5
Standard Deviation: 4.2
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 8](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/08_Day/08_day_objects.md) | [Day 10 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/10_Day/10_day_Set_and_Map.md)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:09 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:09 Day</h1>
<h2>Functional Programming</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>
</html>

@ -0,0 +1,2 @@
console.log(countries)
alert('Open the console and check if the countries has been loaded')

@ -0,0 +1,422 @@
<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 9](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md) | [Day 11>>](#)
![Day 5](../images/banners/day_1_10.png)
- [Day 10](#day-10)
- [Set](#set)
- [Creating an empty set](#creating-an-empty-set)
- [Creating set from array](#creating-set-from-array)
- [Adding an element to a set](#adding-an-element-to-a-set)
- [Deleting an element a set](#deleting-an-element-a-set)
- [Checking an element in the set](#checking-an-element-in-the-set)
- [Clearing the set](#clearing-the-set)
- [Union of sets](#union-of-sets)
- [Intersection of sets](#intersection-of-sets)
- [Difference of sets](#difference-of-sets)
- [Map](#map)
- [Creating an empty Map](#creating-an-empty-map)
- [Creating an Map from array](#creating-an-map-from-array)
- [Adding values to the Map](#adding-values-to-the-map)
- [Getting a value from Map](#getting-a-value-from-map)
- [Checking key in Map](#checking-key-in-map)
- [Exercises](#exercises)
# Day 10
## Set
Set is a collection a collection of elements. Set can only contains unique elements.
Lets see how to create a set
### Creating an empty set
```js
const companies = new Set()
console.log(companies)
```
```sh
{}
```
### Creating set from array
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French'
]
const setOfLangauges = new Set(languages)
console.log(setOfLangauges)
```
```sh
Set(4) {"English", "Finnish", "French", "Spanish"}
```
Set is an iterable object and we can iterate through each elements.
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French'
]
const setOfLangauges = new Set(languages)
for (const language of setOfLangauges) {
console.log(language)
}
```
```sh
English
Finnish
French
Spanish
```
### Adding an element to a set
```js
const companies = new Set() // creating an empty set
console.log(companies.size) // 0
companies.add('Google') // add element to the set
companies.add('Facebook')
companies.add('Amazon')
companies.add('Oracle')
companies.add('Microsoft')
console.log(companies.size) // 5 elements in the set
console.log(companies)
```
```sh
Set(5) {"Google", "Facebook", "Amazon", "Oracle", "Microsoft"}
```
We can also use loop to add element to a set.
```js
const companies = ['Google', 'Facebook', 'Amazon', 'Oracle', 'Microsoft']
setOfCompanies = new Set()
for (const company of companies) {
setOfCompanies.add(company)
}
```
```sh
Set(5) {"Google", "Facebook", "Amazon", "Oracle", "Microsoft"}
```
### Deleting an element a set
We can delete an element from a set using a delete method.
```js
console.log(companies.delete('Google'))
console.log(companies.size) // 4 elements left in the set
```
### Checking an element in the set
The has method can help to know if a certain element exists in a set.
```js
console.log(companies.has('Apple')) // false
console.log(companies.has('Facebook')) // true
```
### Clearing the set
It removes all the elements from a set.
```js
companies.clear()
console.log(companies)
```
```sh
{}
```
See the example below to learn how to use set.
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French'
]
const langSet = new Set(languages)
console.log(langSet) // Set(4) {"English", "Finnish", "French", "Spanish"}
console.log(langSet.size) // 4
const counts = []
const count = {}
for (const l of langSet) {
const filteredLang = languages.filter(lng => lng === l)
console.log(filteredLang) // ["English", "English", "English"]
counts.push({ lang: l, count: filteredLang.length })
}
console.log(counts)
```
```js
[
{ lang: 'English', count: 3 },
{ lang: 'Finnish', count: 1 },
{ lang: 'French', count: 2 },
{ lang: 'Spanish', count: 1 }
]
```
Other use case of set. For instance to count unique item in an array.
```js
const numbers = [5, 3, 2, 5, 5, 9, 4, 5]
const setOfNumbers = new Set(numbers)
console.log(setOfNumbers)
```
```sh
Set(5) {5, 3, 2, 9, 4}
```
### Union of sets
To find a union to two sets can be achieved using spread operator. Lets find the union of set A and set B (A U B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let c = [...a, ...b]
let A = new Set(a)
let B = new Set(b)
let C = new Set(c)
console.log(C)
```
```sh
Set(6) {1, 2, 3, 4, 5,6}
```
### Intersection of sets
To find an intersection of two sets can be achieved using filter. Lets find the union of set A and set B (A ∩ B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let A = new Set(a)
let B = new Set(b)
let c = a.filter(num => B.has(num))
let C = new Set(c)
console.log(C)
```
```sh
Set(3) {3, 4, 5}
```
### Difference of sets
To find an the difference between two sets can be achieved using filter. Lets find the different of set A and set B (A \ B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let A = new Set(a)
let B = new Set(b)
let c = a.filter(num => !B.has(num))
let C = new Set(c)
console.log(C)
```
```sh
Set(2) {1, 2}
```
## Map
### Creating an empty Map
```js
const map = new Map()
console.log(map)
```
```sh
Map(0) {}
```
### Creating an Map from array
```js
countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo']
]
const map = new Map(countries)
console.log(map)
console.log(map.size)
```
```sh
Map(3) {"Finland" => "Helsinki", "Sweden" => "Stockholm", "Norway" => "Oslo"}
3
```
### Adding values to the Map
```js
const countriesMap = new Map()
console.log(countriesMap.size) // 0
countriesMap.set('Finland', 'Helsinki')
countriesMap.set('Sweden', 'Stockholm')
countriesMap.set('Norway', 'Oslo')
console.log(countriesMap)
console.log(countriesMap.size)
```
```sh
Map(3) {"Finland" => "Helsinki", "Sweden" => "Stockholm", "Norway" => "Oslo"}
3
```
### Getting a value from Map
```js
console.log(countriesMap.get('Finland'))
```
```sh
Helsinki
```
### Checking key in Map
Check if a key exist in a map using *has* method. It returns *true* or *false*.
```js
console.log(countriesMap.has('Finland'))
```
```sh
true
```
Getting all values from map using loop
```js
for (const country of countriesMap) {
console.log(country)
}
```
```sh
(2) ["Finland", "Helsinki"]
(2) ["Sweden", "Stockholm"]
(2) ["Norway", "Oslo"]
```
```sh
for (const [country, city] of countriesMap){
console.log(country, city)
}
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
```
🌕 You established a big milestone, you are unstoppable.Keep going! You have just completed day 10 challenges and you are 10 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
1. create an empty set
2. Create a set containing 0 to 10 using loop
3. Remove an element from a set
4. Clear a set
5. Create a set of 5 string elements from array
6. Create a map of countries and number of characters of a country
7. \*\*\* Find the 10 most spoken languages:
````js
// Your output should look like this
console.log(mostSpokenLanguages(countries, 10))
[(91, 'English'),
(45, 'French'),
(25, 'Arabic'),
(24, 'Spanish'),
(9, 'Russian'),
(9, 'Portuguese'),
(8, 'Dutch'),
(7, 'German'),
(5, 'Chinese'),
(4, 'Swahili'),
(4, 'Serbian')]
// Your output should look like this
console.log(mostSpokenLanguages(countries, 3))
[
(91, 'English'),
(45, 'French'),
(25, 'Arabic')
]```
````
🎉 CONGRATULATIONS ! 🎉
[<< Day 9](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md) | [Day 11>>](#)

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 73 KiB

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

Before

Width:  |  Height:  |  Size: 76 KiB

After

Width:  |  Height:  |  Size: 76 KiB

@ -1,7 +1,19 @@
## Table of Contents <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 2 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/02_Day/02_day_data_types.md) [Day 2 >>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/02_Day/02_day_data_types.md)
--
![Thirty Days Of JavaScript](./images/day_1_1.png) ![Thirty Days Of JavaScript](./images/day_1_1.png)
@ -227,10 +239,15 @@ If you installed visual studio code, let us start using it.
Open the visual studio code by double-clicking the visual studio icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons. Open the visual studio code by double-clicking the visual studio icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons.
![Vscode ui](./images/vscode_ui.png) ![Vscode ui](./images/vscode_ui.png)
![Vscode add project](./images/adding_project_to_vscode.png) ![Vscode add project](./images/adding_project_to_vscode.png)
![Vscode open project](./images/opening_project_on_vscode.png) ![Vscode open project](./images/opening_project_on_vscode.png)
![script file](images/scripts_on_vscode.png) ![script file](images/scripts_on_vscode.png)
![running script](./images/running_script.png) ![running script](./images/running_script.png)
![coding running](./images/launched_on_new_tab.png) ![coding running](./images/launched_on_new_tab.png)
## Adding JavaScript to a web page ## Adding JavaScript to a web page
@ -298,6 +315,7 @@ This is how we write the internal script most of the time. Writing the JavaScrip
``` ```
Open the browser console to see the output from the console.log() Open the browser console to see the output from the console.log()
![js code from vscode](./images/js_code_vscode.png) ![js code from vscode](./images/js_code_vscode.png)
### External script ### External script
@ -320,7 +338,7 @@ External scripts in the head
</head> </head>
<body> <body>
</body> </body>
</html </html>
``` ```
External scripts in the body External scripts in the body
@ -336,7 +354,7 @@ External scripts in the body
// Here is the recommended place to put the external script // Here is the recommended place to put the external script
<script src="introduction.js"></script> <script src="introduction.js"></script>
</body> </body>
</html </html>
``` ```
Open the browser console to see the output from the console.log() Open the browser console to see the output from the console.log()
@ -361,10 +379,11 @@ console.log('Hello, World!')
<script src ="./helloworld.js"></script> <script src ="./helloworld.js"></script>
<script src="./introduction.js"></script> <script src="./introduction.js"></script>
</body> </body>
</html </html>
``` ```
Your main.js file should be below all other scripts. Watch out your exercise needs to understand this line. Your main.js file should be below all other scripts. Watch out your exercise needs to understand this line.
![Multiple Script](./images/multiple_script.png) ![Multiple Script](./images/multiple_script.png)
## Introduction to Data types ## Introduction to Data types
@ -403,8 +422,8 @@ A boolean data type is either a True or False value.
**Example:** **Example:**
```js ```js
true # if the light on ,the value is true true // if the light on ,the value is true
false # if the light off, the value is False false // if the light off, the value is False
``` ```
### Undefined ### Undefined
@ -421,7 +440,7 @@ console.log(firstName); //not defined, because it is not assigned to a value yet
Null in JavaScript means an empty value. Null in JavaScript means an empty value.
```js ```js
let emptyValue = nulll let emptyValue = null
``` ```
## Checking Data types ## Checking Data types
@ -431,8 +450,8 @@ To check the data type of a certain data type, we use the **typeof** operator. S
```js ```js
console.log(typeof 'Asabeneh') // string console.log(typeof 'Asabeneh') // string
console.log(typeof 5) // number console.log(typeof 5) // number
console.log(typeof true ) // boolean console.log(typeof true ) // boolean
console.log(typeof null) // object type console.log(typeof null) // object type
console.log(typeof undefined) // undefined console.log(typeof undefined) // undefined
``` ```
@ -445,6 +464,7 @@ There are two ways of commenting:
- _Multiline commenting_ - _Multiline commenting_
```js ```js
// commenting the code itself with a single comment
// let firstName = 'Asabeneh'; single line comment // let firstName = 'Asabeneh'; single line comment
// let lastName = 'Yetayeh'; single line comment // let lastName = 'Yetayeh'; single line comment
``` ```
@ -466,10 +486,10 @@ Variables are _containers_ of data. Variables used to _store_ data in a memory l
For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do no change, and we can use *const*. For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do no change, and we can use *const*.
* A JavaScript variable name should not begin with a number. - A JavaScript variable name should not begin with a number.
* A JavaScript variable name does not allow special characters except dollar sign and underscore. - A JavaScript variable name does not allow special characters except dollar sign and underscore.
* A JavaScript variable name follows a camelCase convention. - A JavaScript variable name follows a camelCase convention.
* A JavaScript variable name should not have space between words. - A JavaScript variable name should not have space between words.
The following are valid examples of JavaScript variables. The following are valid examples of JavaScript variables.
Valid variables in JavaScript: Valid variables in JavaScript:
@ -516,26 +536,46 @@ Let us declare variables with different data types. To declare a variable, we ne
```js ```js
// Declaring different variables of different data types // Declaring different variables of different data types
let firstName = 'Asabeneh' // first name of a person
let lastName = 'Yetayeh' // last name of a person
let country = 'Finland' // country
let city = 'Helsinki' // capital city
let age = 100 // age in years
let isMarried = true
console.log(firstName, lastName, country, city, age, isMarried); //Asabeneh, Yetayeh, Finland, Helsinki, 100, True
let firstName = 'Asabeneh' // first name of a person
let lastName = 'Yetayeh' // last name of a person
let country = 'Finland' // country
let city = 'Helsinki' // capital city
let isMarried = true // boolean data type
console.log(firstName, lastName, country, city, age, isMarried)
```
```sh
Asabeneh Yetayeh Finland Helsinki 100 True
```
```js
// Declaring variables with number values // Declaring variables with number values
const gravity = 9.81; // earth gravity in m/s2 let age = 100 // age in years
const boilingPoint = 100; // water boiling point, temperature in oC const gravity = 9.81 // earth gravity in m/s2
const PI = 3.14; // geometrical constant const boilingPoint = 100 // water boiling point, temperature in oC
console.log(gravity, boilingPoint, PI); // 9.81, 100, 3.14 const PI = 3.14 // geometrical constant
console.log(gravity, boilingPoint, PI)
```
```sh
9.81 100 3.14
```
```js
// Variables can also be declaring in one line separated by comma // Variables can also be declaring in one line separated by comma
let name = 'Asabeneh', //name of a person let name = 'Asabeneh', // name of a person
job = 'teacher', job = 'teacher',
live = 'Finland'; live = 'Finland';
console.log(name, job, live); console.log(name, job, live);
``` ```
```sh
Asabeneh teacher Finland
```
When you run the files on 01-Day folder you should get this: When you run the files on 01-Day folder you should get this:
![Day one](./images/day_1.png) ![Day one](./images/day_1.png)

Loading…
Cancel
Save