Merge pull request #1 from Asabeneh/master

Updating my fork
pull/147/head
Esra Dogan 6 years ago committed by GitHub
commit 807f532cc5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

23
.gitignore vendored

@ -14,23 +14,6 @@ day9.md
day10.md
01_02_03_days_backup.md
test.md
12_Day
13_Day
14_Day
15_Day
16_Day
17_Day
18_Day
19_Day
20_Day
21_Day
22_Day
23_Day
24_Day
25_Day
26_Day
27_Day
28_Day
29_Day
30_Day
test.html
31_Day
test.html
res.js

@ -1,17 +0,0 @@
// 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,3 +1,4 @@
// the variable values can be accessed from other variable.js file
console.log(firstName, lastName, country, city, age, isMarried)
console.log(gravity, boilingPoint, PI) // 9.81, 100, 3.14
console.log(name, job, live)

@ -0,0 +1,20 @@
// 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,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Data Types</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>
@ -14,48 +14,51 @@
</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](../readMe.md) | [Day 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)
![Thirty Days Of JavaScript](../images/banners/day_1_2.png)
- [📔 Day 2](#%f0%9f%93%94-day-2)
- [Data types](#data-types)
- [📔 Day 2](#-day-2)
- [Data Types](#data-types)
- [Primitive Data Types](#primitive-data-types)
- [Non-Primitive Data Types](#non-primitive-data-types)
- [Numbers](#numbers)
- [Declaring number data types](#declaring-number-data-types)
- [Declaring Number Data Types](#declaring-number-data-types)
- [Math Object](#math-object)
- [Random number generator](#random-number-generator)
- [Random Number Generator](#random-number-generator)
- [Strings](#strings)
- [String Concatenation](#string-concatenation)
- [Concatenating using addition operator](#concatenating-using-addition-operator)
- [Concatenating Using Addition Operator](#concatenating-using-addition-operator)
- [Long Literal Strings](#long-literal-strings)
- [Escape Sequences in string](#escape-sequences-in-string)
- [Template Literals(Template Strings)](#template-literalstemplate-strings)
- [Escape Sequences in Strings](#escape-sequences-in-strings)
- [Template Literals (Template Strings)](#template-literals-template-strings)
- [String Methods](#string-methods)
- [Checking Data types and Casting](#checking-data-types-and-casting)
- [Checking data types](#checking-data-types)
- [Changing data type(Casting)](#changing-data-typecasting)
- [Checking Data Types and Casting](#checking-data-types-and-casting)
- [Checking Data Types](#checking-data-types)
- [Changing Data Type (Casting)](#changing-data-type-casting)
- [String to Int](#string-to-int)
- [String to Float](#string-to-float)
- [Float to Int](#float-to-int)
- [💻 Day 2: Exercises](#%f0%9f%92%bb-day-2-exercises)
- [💻 Day 2: Exercises](#-day-2-exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 2
## Data types
## Data Types
In the previous section, we mentioned a little bit about data types. Data or values have data types. Data types describe the characteristics of data. Data types can be divided into two
In the previous section, we mentioned a little bit about data types. Data or values have data types. Data types describe the characteristics of data. Data types can be divided into two:
1. Primitive data types
2. Non-primitive data types(Object References)
### Primitive Data Types
Primitive data types in JavaScript includes:
Primitive data types in JavaScript include:
1. Numbers - Integers, floats
2. Strings - Any data under single or double quote
2. Strings - Any data under single quote, double quote or backtick quote
3. Booleans - true or false value
4. Null - empty value or no value
5. Undefined - a declared variable without a value
@ -66,21 +69,22 @@ Non-primitive data types in JavaScript includes:
2. Functions
3. Arrays
Now, let us see what exactly mean primitive and non-primitive data types.
*Primitive* data types are immutable(non-modifiable) data types. Once a primitive data type is created we can not modify it.
Now, let us see what exactly primitive and non-primitive data types mean.
*Primitive* data types are immutable(non-modifiable) data types. Once a primitive data type is created we cannot modify it.
**Example:**
```js
let word = 'JavaScript'
```
If we try to modify the string stored in variable *word*, JavaScript will raise an error. Any data type under a single quote, double-quote, or backtick is a string data type.
If we try to modify the string stored in variable *word*, JavaScript should raise an error. Any data type under a single quote, double quote, or backtick quote is a string data type.
```js
word[0] = 'Y'
```
This expression does not change the string stored in the variable *word*. So, we can say that strings are not modifiable or immutable.
This expression does not change the string stored in the variable *word*. So, we can say that strings are not modifiable or in other words immutable.
Primitive data types are compared by its values. Let us compare different data values. See the example below:
```js
@ -112,7 +116,7 @@ nums[0] = 10
console.log(nums) // [10, 2, 3]
```
As you can see, an array in which a non-primitive data type is mutable. Non-primitive data types can not be compared by value. Even if two non-primitive data types have the same properties and values, they are not strictly equal.
As you can see, an array, which is a non-primitive data type is mutable. Non-primitive data types cannot be compared by value. Even if two non-primitive data types have the same properties and values, they are not strictly equal.
```js
let nums = [1, 2, 3]
@ -132,11 +136,11 @@ role:'teaching',
country:'Finland'
}
console.log(userOne == userTwo)
console.log(userOne == userTwo) // false
```
Rule of thumb, we do not compare non-primitive data types. Do not compare array, function, or object.
Non-primitive values are referred to as reference types because they are being compared by reference instead of value. Two objects are only strictly equal if they refer to the same underlying object.
Rule of thumb, we do not compare non-primitive data types. Do not compare arrays, functions, or objects.
Non-primitive values are referred to as reference types, because they are being compared by reference instead of value. Two objects are only strictly equal if they refer to the same underlying object.
```js
let nums = [1, 2, 3]
@ -160,17 +164,17 @@ If you have a hard time understanding the difference between primitive data type
## Numbers
Numbers are integers and decimal values which can do all the arithmetic operations.
Lets' see some examples of Numbers.
Let's see some examples of Numbers.
### Declaring number data types
### Declaring Number Data Types
```js
let age = 35
const gravity = 9.81 //we use const for non-changing values, gravitational constant in m/s2
const gravity = 9.81 // we use const for non-changing values, gravitational constant in m/s2
let mass = 72 // mass in Kilogram
const PI = 3.14 // pi a geometrical constant
//More Examples
// More Examples
const boilingPoint = 100 // temperature in oC, boiling point of water which is a constant
const bodyTemp = 37 // oC average human body temperature, which is a constant
@ -184,22 +188,22 @@ In JavaScript the Math Object provides a lots of methods to work with numbers.
```js
const PI = Math.PI
console.log(PI) // 3.141592653589793
console.log(PI) // 3.141592653589793
// Rounding to the closest number
// if above .5 up if less 0.5 down rounding
console.log(Math.round(PI)) // 3 to round values to the nearest number
console.log(Math.round(PI)) // 3 to round values to the nearest number
console.log(Math.round(9.81)) // 10
console.log(Math.round(9.81)) // 10
console.log(Math.floor(PI)) // 3 rounding down
console.log(Math.floor(PI)) // 3 rounding down
console.log(Math.ceil(PI)) // 4 rounding up
console.log(Math.ceil(PI)) // 4 rounding up
console.log(Math.min(-5, 3, 20, 4,5, 10)) // -5, returns the minimum value
console.log(Math.min(-5, 3, 20, 4, 5, 10)) // -5, returns the minimum value
console.log(Math.max(-5, 3, 20, 4,5, 10)) // 20, returns the maximum value
console.log(Math.max(-5, 3, 20, 4, 5, 10)) // 20, returns the maximum value
const randNum = Math.random() // creates random number between 0 to 0.999999
console.log(randNum)
@ -210,22 +214,22 @@ const num = Math.floor(Math.random () * 11) // creates random number between 0 a
console.log(num)
//Absolute value
console.log(Math.abs(-10)) //10
console.log(Math.abs(-10)) // 10
//Square root
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) //1.4142135623730951
console.log(Math.sqrt(2)) // 1.4142135623730951
// Power
console.log(Math.pow(3, 2)) // 9
console.log(Math.pow(3, 2)) // 9
console.log(Math.E) // 2.718
console.log(Math.E) // 2.718
// Logarithm
//Returns the natural logarithm of base E of x, Math.log(x)
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
// Returns the natural logarithm with base E of x, Math.log(x)
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
// Trigonometry
Math.sin(0)
@ -235,15 +239,15 @@ Math.cos(0)
Math.cos(60)
```
#### Random number generator
#### Random Number Generator
The JavaScript Math Object has a random() method number generator which generates number from 0 to 0.999999999...
```js
let randomNum = Math.random() // generates 0 to 0.999
let randomNum = Math.random() // generates 0 to 0.999...
```
Now, let us see how we can use random() method to generate a random number between 0 and 10 inclusive.
Now, let us see how we can use random() method to generate a random number between 0 and 10:
```js
let randomNum = Math.random() // generates 0 to 0.999
@ -257,8 +261,8 @@ console.log(randomNumRoundToFloor) // this gives between 0 and 10
## Strings
Strings are texts, which are under **_single_** or **_double_** quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double-quote, or backtick.
Lets' see some examples of string:
Strings are texts, which are under **_single_** , **_double_**, **_back-tick_** quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double quote, or backtick quote.
Let's see some examples of strings:
```js
let space = ' ' // an empty space string
@ -268,22 +272,14 @@ let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let quote = "The saying,'Seeing is Believing' is not correct in 2020."
let quotWithBackTick = `The saying,'Seeing is Believing' is not correct in 2020.`
```
### String Concatenation
Connect two or more strings together is called concatenation.
```js
// Declaring different variables of different data types
let space = ' '
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
```
Connecting two or more strings together is called concatenation.
Using the strings declared in the previous String section:
```js
let fullName = firstName + space + lastName; // concatenation, merging two string together.
@ -294,11 +290,11 @@ console.log(fullName);
Asabeneh Yetayeh
```
We can concatenate string in different ways.
We can concatenate strings in different ways.
#### Concatenating using addition operator
#### Concatenating Using Addition Operator
Concatenating using the addition operator is an old way. This way of concatenating is tedious and error-prone. It is good to know how to concatenate this way, but I strongly suggest to use the second way.
Concatenating using the addition operator is an old way. This way of concatenating is tedious and error-prone. It is good to know how to concatenate this way, but I strongly suggest to use the ES6 template strings (explained later on).
```js
// Declaring different variables of different data types
@ -310,9 +306,10 @@ let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let age = 250
let fullName = firstName + space + lastName
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country; // ES5
let fullName =firstName + space + lastName
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country; // ES5 string addition
console.log(personInfoOne)
```
@ -335,35 +332,52 @@ to global audience and I started a Python challenge from November 20 - December
It was one of the most rewarding and inspiring experience.\
Now, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \
I hope you are enjoying too."
console.log(paragraph)
```
#### Escape Sequences in string
#### Escape Sequences in Strings
In JavaScript and other programming language \ followed by some characters is an escape sequence. Let's see the most common escape characters:
In JavaScript and other programming languages \ followed by some characters is an escape sequence. Let's see the most common escape characters:
- \n: new line
- \t: Tab means(8 spaces)
- \t: Tab, means 8 spaces
- \\\\: Back slash
- \\': Single quote (')
- \\":Double quote (")
- \\": Double quote (")
```js
console.log('I hope every one is enjoying the 30 Days Of JavaScript challenge.\nDo you ?') // line break
console.log('I hope everyone is enjoying the 30 Days Of JavaScript challenge.\nDo you ?') // line break
console.log('Days\tTopics\tExercises')
console.log('Day 1\t3\t5')
console.log('Day 2\t3\t5')
console.log('Day 3\t3\t5')
console.log('Day 4\t3\t5')
console.log('This is a back slash symbol (\\)') // To write a back slash
console.log('This is a backslash symbol (\\)') // To write a backslash
console.log('In every programming language it starts with \"Hello, World!\"')
console.log("In every programming language it starts with \'Hello, World!\'")
console.log('The saying \'Seeing is Believing\' is\'t correct in 2020')
console.log('The saying \'Seeing is Believing\' isn\'t correct in 2020')
```
Output in console:
```sh
I hope everyone is enjoying the 30 Days Of JavaScript challenge.
Do you ?
Days Topics Exercises
Day 1 3 5
Day 2 3 5
Day 3 3 5
Day 4 3 5
This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
In every programming language it starts with 'Hello, World!'
The saying 'Seeing is Believing' isn't correct in 2020
```
#### Template Literals(Template Strings)
#### Template Literals (Template Strings)
To create a template string, we use two backticks. We can inject data as expression inside a template string. To inject data, we enclose the expression with a curly bracket({}) followed by a $ sign. See the syntax below.
To create a template strings, we use two back-ticks. We can inject data as expressions inside a template string. To inject data, we enclose the expression with a curly bracket({}) preceded by a $ sign. See the syntax below.
```js
//Syntax
@ -403,7 +417,7 @@ I am Asabeneh Yetayeh. I am 250. I live in Finland.
I am Asabeneh Yetayeh. I live in Helsinki, Finland. I am a teacher. I teach JavaScript.
```
Using a string template or string interpolation method, we can add expression, which could be a value or some operations(comparison, arithmetic operations, ternary operation).
Using a string template or string interpolation method, we can add expressions, which could be a value, or some operations (comparison, arithmetic operations, ternary operation).
```js
let a = 2
@ -417,19 +431,20 @@ console.log(`${a} is greater than ${b}: ${a > b}`)
### String Methods
Everything in JavaScript is an object. A string is a primitive data type that means we can not modify once it is created. The string object has many string methods. There are different string methods that can help us to work with strings.
Everything in JavaScript is an object. A string is a primitive data type that means we can not modify it once it is created. The string object has many string methods. There are different string methods that can help us to work with strings.
1. *length*: The string *length* method returns the number of characters in a string included empty space.
**Example:**
```js
let js = 'JavaScript'
console.log(js.length) // 10
let firstName = 'Asabeneh'
console.log(firstName.length) // 8
```
**Example:**
```js
let js = 'JavaScript'
console.log(js.length) // 10
let firstName = 'Asabeneh'
console.log(firstName.length) // 8
```
2. *Accessing characters in a string*: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is one minus the length of the string.
2. *Accessing characters in a string*: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is the length of the string minus one.
![Accessing sting by index](../images/string_indexes.png)
@ -453,7 +468,7 @@ console.log(lastIndex) // 9
console.log(string[lastIndex]) // t
```
1. *toUpperCase()*: this method changes the string to uppercase letters.
3. *toUpperCase()*: this method changes the string to uppercase letters.
```js
let string = 'JavaScript'
@ -495,7 +510,7 @@ let country = 'Finland'
console.log(country.substr(3, 4)) // land
```
6. *substring()*: It takes two arguments, the starting index and the stopping index but it doesn't include the stopping index.
6. *substring()*: It takes two arguments, the starting index and the stopping index but it doesn't include the character at the stopping index.
```js
let string = 'JavaScript'
@ -516,17 +531,17 @@ console.log(country.substring(3)) // land
```js
let string = '30 Days Of JavaScript'
console.log(string.split()) // ["30 Days Of JavaScript"]
console.log(string.split(' ')) // ["30", "Days", "Of", "JavaScript"]
console.log(string.split()) // Changes to an array -> ["30 Days Of JavaScript"]
console.log(string.split(' ')) // Split to an array at space -> ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh'
console.log(firstName.split()) // ["Asabeneh"]
console.log(firstName.split('')) // ["A", "s", "a", "b", "e", "n", "e", "h"]
console.log(firstName.split()) // Change to an array - > ["Asabeneh"]
console.log(firstName.split('')) // Split to an array at each letter -> ["A", "s", "a", "b", "e", "n", "e", "h"]
let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(countries.split(',')) // ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(',')) // split to any array at comma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
```
@ -535,13 +550,13 @@ console.log(countries.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark
```js
let string = ' 30 Days Of JavaScript '
console.log(string)
console.log(string)
console.log(string.trim(' '))
let firstName = ' Asabeneh '
console.log(firstName)
console.log(firstName.trim())
console.log(firstName.trim()) // still removes spaces at the beginning and the end of the string
```
```sh
@ -551,13 +566,13 @@ console.log(firstName.trim())
Asabeneh
```
9. *includes()*: It takes a substring argument and it check if substring argument exists in the string. *includes()* returns a boolean. It checks if a substring exist in a string and it returns true if it exists and false if it doesn't exist.
9. *includes()*: It takes a substring argument and it checks if substring argument exists in the string. *includes()* returns a boolean. If a substring exist in a string, it returns true, otherwise it returns false.
```js
let string = '30 Days Of JavaScript'
console.log(string.includes('Days')) // true
console.log(string.includes('days')) // false
console.log(string.includes('days')) // false - it is case sensitive!
console.log(string.includes('Script')) // true
console.log(string.includes('script')) // false
console.log(string.includes('java')) // false
@ -571,7 +586,7 @@ console.log(country.includes('land')) // true
console.log(country.includes('Land')) // false
```
10. *replace()*: takes to parameter the old substring and new substring.
10. *replace()*: takes as a parameter the old substring and a new substring.
```js
string.replace(oldsubstring, newsubstring)
@ -599,7 +614,7 @@ let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)) // t
```
12. *charCodeAt()*: Takes index and it returns char code(ASCII number) of the value at that index
12. *charCodeAt()*: Takes index and it returns char code (ASCII number) of the value at that index
```js
string.charCodeAt(index)
@ -607,14 +622,14 @@ string.charCodeAt(index)
```js
let string = '30 Days Of JavaScript'
console.log(string.charCodeAt(3)) // D ASCII number is 51
console.log(string.charCodeAt(3)) // D ASCII number is 68
let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)) // t ASCII is 116
```
13. *indexOf()*: Takes takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1
13. *indexOf()*: Takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1
```js
string.indexOf(substring)
@ -632,10 +647,12 @@ console.log(string.indexOf('Script')) //15
console.log(string.indexOf('script')) // -1
```
14. *lastIndexOf()*: Takes takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1
14. *lastIndexOf()*: Takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1
```js
string.lastIndexOf(index)
//syntax
string.lastIndexOf(substring)
```
```js
@ -646,7 +663,7 @@ console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38
```
15. *concat()*: it takes many substrings and creates concatenation.
15. *concat()*: it takes many substrings and joins them.
```js
string.concat(substring, substring, substring)
@ -681,18 +698,18 @@ console.log(country.startsWith('fin')) // false
console.log(country.startsWith('land')) // false
```
17. *endsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
17. *endsWith*: it takes a substring as an argument and it checks if the string ends with that specified substring. It returns a boolean(true or false).
```js
string.endsWith(substring)
```
```js
let string = 'Love is the best to in this world'
let string = 'Love is the most powerful feeling in the world'
console.log(string.endsWith('world')) // true
console.log(string.endsWith('love')) // false
console.log(string.endsWith('in this world')) // true
console.log(string.endsWith('in the world')) // true
let country = 'Finland'
@ -701,7 +718,7 @@ console.log(country.endsWith('fin')) // false
console.log(country.endsWith('Fin')) // false
```
18. *search*: it takes a substring as an argument and it returns the index of the first match.
18. *search*: it takes a substring as an argument and it returns the index of the first match. The search value can be a string or a regular expression pattern.
```js
string.search(substring)
@ -709,7 +726,8 @@ string.search(substring)
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2
console.log(string.search('love')) // 2
console.log(string.search(/javascript/gi)) // 7
```
19. *match*: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign.
@ -741,10 +759,10 @@ let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
```
Let us extract numbers from text using regular expression. This is not regular expression section, no panic, we will cover regular expression in other section.
Let us extract numbers from text using a regular expression. This is not the regular expression section, do not panic! We will cover regular expressions later on.
```js
let txt = 'In 2019, I run 30 Days of Python. Now, in 2020 I super exited to start this challenge'
let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge'
let regEx = /\d+/
// d with escape character means d not a normal d instead acts a digit
@ -755,7 +773,7 @@ console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2",
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
```
20. *repeat()*: it takes a number argument and it returned the repeated version of the string.
20. *repeat()*: it takes a number as argument and it returns the repeated version of the string.
```js
string.repeat(n)
@ -766,12 +784,13 @@ let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
```
## Checking Data types and Casting
## Checking Data Types and Casting
### Checking data types
### Checking Data Types
- Check Data types: To check the data type of a certain data type we use the _typeof_ and we also change one data type to another.
**Example:**
To check the data type of a certain variable we use the _typeof_ method.
**Example:**
```js
// Different javascript data types
@ -796,14 +815,14 @@ console.log(typeof undefined) // undefined
console.log(typeof null) // object
```
### Changing data type(Casting)
### Changing Data Type (Casting)
- Casting: Converting one data type to another data type. We use _parseInt()_, _parsefloat()_,_Number()_, _+ sign_, _str()_
- Casting: Converting one data type to another data type. We use _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_
When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error.
#### String to Int
We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: '10', '5', etc.
We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: '10', '5', etc.
We can convert string to number using the following methods:
- parseInt()
@ -832,7 +851,7 @@ console.log(numInt) // 10
#### String to Float
We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc.
We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc.
We can convert string float to number using the following methods:
- parseFloat()
@ -874,76 +893,84 @@ let numInt = parseInt(num)
console.log(numInt) // 9
```
🌕 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.
🌕 You are awesome. You have just completed day 2 challenges and you are two steps ahead on your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Day 2: Exercises
# 💻 Day 2: Exercises
### Exercise: Level 1
1. Declare a variable name challenge and assign it to an initial value **'30 Days Of JavaScript'**.
1. Declare a variable named challenge and assign it to an initial value **'30 Days Of JavaScript'**.
2. Print the string on the browser console using __console.log()__
3. Print the __length__ of the string on the browser console using _console.log()_
4. Change all the string to capital letters using __toUpperCase()__ method
5. Change all the string to lowercase letters using __toLowerCase()__ method
6. Cut(slice) out the first word of the string using __substr()__ or __substring()__ method
4. Change all the string characters to capital letters using __toUpperCase()__ method
5. Change all the string characters to lowercase letters using __toLowerCase()__ method
6. Cut (slice) out the first word of the string using __substr()__ or __substring()__ method
7. Slice out the phrase *Days Of JavaScript* from *30 Days Of JavaScript*.
8. Use __substr__ to slice out the phase __because because because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
9. Check if the string contains a word __Script__ using __includes()__ method
10. Split the __string__ into __array__ using __split()__ method
11. Split the string 30 Days Of JavaScript at the space using __split()__ method
12. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array.
13. Change 30 Days Of JavaScript to 30 Days Of Python using __replace()__ method.
14. What is character at index 15 in '30 Days Of JavaScript' string use __charAt()__ method.
15. What is the character code of J in '30 Days Of JavaScript' string using __charCodeAt()__
16. Use __indexOf__ to determine the position of the first occurrence of a in 30 Days Of JavaScript
17. Use __lastIndexOf__ to determine the position of the last occurrence of a in 30 Days Of JavaScript.
18. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
19. Use __lastIndexOf__ to find the position of the last occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
20. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
21. Use __trim()__ to remove if there is trailing whitespace at the beginning and the end of a string.E.g ' 30 Days Of JavaScript '.
22. Use __startsWith()__ method with the string *30 Days Of JavaScript* make the result true
23. Use __endsWith()__ method with the string *30 Days Of JavaScript* make the result true
24. Use __match()__ method to find all the as in 30 Days Of JavaScript
25. Use __match()__ to count the number all because's in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
26. Use __concat()__ and merge '30 Days of' and 'JavaScript' to a single string, '30 Days Of JavaScript'
27. Use __repeat()__ method to print 30 Days Of JavaScript 2 times
28. ** 'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word love in this sentence.
29. ** Calculate the total annual income of the person by extract the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'
30. ** Clean the following text and find the most frequent word(hint, use replace and regular express).
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is also $the $result of &love& of tea&ching'
```
31. Using console.log() print out the following statement.
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help to one another.
```
32. Using console.log() print out the following quote by Mother Teresa.
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
33. Check if 'on' is found in both python and jargon
34. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence.
35. Generate a random number between 0 and 100 inclusive.
36. Generate a random number between 50 and 100 inclusive.
37. Generate a random number between 0 and 255 inclusive.
38. Access the 'JavaScript' string characters using a random number.
39. Use console.log() and escape characters to print the following pattern.
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
40. Check if typeof '10' is exactly equal to 10. If not make it exactly equal.
41. Check if parseInt('9.8') is equal to 10 if not make it exactly equal with 10.
8. Check if the string contains a word __Script__ using __includes()__ method
9. Split the __string__ into an __array__ using __split()__ method
10. Split the string 30 Days Of JavaScript at the space using __split()__ method
11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array.
12. Change 30 Days Of JavaScript to 30 Days Of Python using __replace()__ method.
13. What is character at index 15 in '30 Days Of JavaScript' string? Use __charAt()__ method.
14. What is the character code of J in '30 Days Of JavaScript' string using __charCodeAt()__
15. Use __indexOf__ to determine the position of the first occurrence of __a__ in 30 Days Of JavaScript
16. Use __lastIndexOf__ to determine the position of the last occurrence of __a__ in 30 Days Of JavaScript.
17. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
18. Use __lastIndexOf__ to find the position of the last occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
19. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
20. Use __trim()__ to remove any trailing whitespace at the beginning and the end of a string.E.g ' 30 Days Of JavaScript '.
21. Use __startsWith()__ method with the string *30 Days Of JavaScript* and make the result true
22. Use __endsWith()__ method with the string *30 Days Of JavaScript* and make the result true
23. Use __match()__ method to find all the __a__s in 30 Days Of JavaScript
24. Use __concat()__ and merge '30 Days of' and 'JavaScript' to a single string, '30 Days Of JavaScript'
25. Use __repeat()__ method to print 30 Days Of JavaScript 2 times
### Exercise: Level 2
1. Using console.log() print out the following statement:
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help one another.
```
2. Using console.log() print out the following quote by Mother Teresa:
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
3. Check if typeof '10' is exactly equal to 10. If not make it exactly equal.
4. Check if parseFloat('9.8') is equal to 10 if not make it exactly equal with 10.
5. Check if 'on' is found in both python and jargon
6. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence.
7. Generate a random number between 0 and 100 inclusively.
8. Generate a random number between 50 and 100 inclusively.
9. Generate a random number between 0 and 255 inclusively.
10. Access the 'JavaScript' string characters using a random number.
11. Use console.log() and escape characters to print the following pattern.
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
12. Use __substr__ to slice out the phrase __because because because__ from the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
### Exercises: Level 3
1. 'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word __love__ in this sentence.
2. Use __match()__ to count the number of all __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
3. Clean the following text and find the most frequent word (hint, use replace and regular expressions).
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching'
```
4. Calculate the total annual income of the person by extracting the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'
🎉 CONGRATULATIONS ! 🎉
[<< 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](../readMe.md) | [Day 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 75 KiB

@ -15,8 +15,8 @@ console.log(string.match(pattern)) // ["love", "love", "love"]
// Let us extract numbers from text using regular expression. This is not regular expression section, no panic.
let txt = 'In 2019, I run 30 Days of Pyhton. Now, in 2020 I super exited to start this challenge'
let regEx = /\d+/ // d with escape character means d not a normal d instead acts a digit
let regEx = /\d/g // d with escape character means d not a normal d instead acts a digit
// + means one or more digit numbers,
// if there is g after that it means global, search everywhere.
console.log(text.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(text.match(/\d+/g)) // ["2019", "30", "2020"]
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Booleans, Operators, Date</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>
@ -13,11 +13,11 @@
</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](../02_Day_Data_types/02_day_data_types.md) | [Day 4 >>](../04_Day_Conditionals/04_day_conditionals.md)
![Thirty Days Of JavaScript](../images/banners/day_1_3.png)
- [📔 Day 3](#%f0%9f%93%94-day-3)
- [📔 Day 3](#-day-3)
- [Booleans](#booleans)
- [Truthy values](#truthy-values)
- [Falsy values](#falsy-values)
@ -46,14 +46,10 @@
- [Getting minutes](#getting-minutes)
- [Getting seconds](#getting-seconds)
- [Getting time](#getting-time)
- [💻 Day 3: Exercises](#%f0%9f%92%bb-day-3-exercises)
- [1. Exercises: Data types Part](#1-exercises-data-types-part)
- [2. Exercises: Arithmetic Operators Part](#2-exercises-arithmetic-operators-part)
- [3. Exercises: Booleans Part](#3-exercises-booleans-part)
- [4. Exercises: Comparison Operators](#4-exercises-comparison-operators)
- [5. Exercises: Logical Operators](#5-exercises-logical-operators)
- [6 Ternary Operator](#6-ternary-operator)
- [7. Exercises: Date time Object](#7-exercises-date-time-object)
- [💻 Day 3: Exercises](#-day-3-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 3
@ -68,8 +64,8 @@ let isLightOn = true
let isRaining = false
let isHungry = false
let isMarried = true
let truValue = 4 > 3 // true
let falseValue = 3 < 4 // false
let truValue = 4 > 3 // true
let falseValue = 4 < 3 // false
```
We agreed that boolean values are either true or false.
@ -90,11 +86,11 @@ We agreed that boolean values are either true or false.
- the boolean false
- '', "", ``, empty string
It is good to remember those truthy values and falsy values. In later section, we will use them with conditions to make decision.
It is good to remember those truthy values and falsy values. In later section, we will use them with conditions to make decisions.
## Undefined
If we declare a variable and if we do not assign a value, the value will be undefined. In addition to this, if a function is not returning the value will be undefined.
If we declare a variable and if we do not assign a value, the value will be undefined. In addition to this, if a function is not returning the value, it will be undefined.
```js
let firstName
@ -129,10 +125,10 @@ Arithmetic operators are mathematical operators.
- Addition(+): a + b
- Subtraction(-): a - b
- Multiplication(_): a _ b
- Multiplication(*): a * b
- Division(/): a / b
- Modulus(%):a % b
- Exponential(**):a ** b
- Modulus(%): a % b
- Exponential(**): a ** b
```js
let numOne = 4
@ -146,23 +142,29 @@ let powerOf = numOne ** numTwo
console.log(sum, diff, mult, div, remainder, powerOf) // 7,1,12,1.33,1, 64
let PI = 3.14
let radius = 100 // length in meter
```
const gravity = 9.81 // in m/s2
let mass = 72 // in Kilogram
const boilingPoint = 100 // temperature in oC, boiling point of water
const bodyTemp = 37 // body temperature in oC
```js
const PI = 3.14
let radius = 100 // length in meter
//Let us calculate area of a circle
const areaOfCircle = PI * radius * radius
console.log(areaOfCircle) // 314 m
const gravity = 9.81 // in m/s2
let mass = 72 // in Kilogram
// Let us calculate weight of an object
const weight = mass * gravity
console.log(weight) // 706.32 N(Newton)
//Concatenating string with numbers using string interpolation
const boilingPoint = 100 // temperature in oC, boiling point of water
const bodyTemp = 37 // body temperature in oC
// Concatenating string with numbers using string interpolation
/*
The boiling point of water is 100 oC.
Human body temperature is 37 oC.
@ -191,14 +193,13 @@ console.log(3 != 2) // true, because 3 is not equal to 2
console.log(3 == '3') // true, compare only value
console.log(3 === '3') // false, compare both value and data type
console.log(3 !== '3') // true, compare both value and data type
console.log(3 !== '3') // true, compare both value and data type
console.log(3 != 3) // false, compare only value
console.log(3 !== 3) // false, compare both value and data type
console.log(0 == false) // true, equivalent
console.log(0 === false) // false, not exactly the same
console.log(0 == '') // true, equivalent
console.log(0 == ' ') // true, equivalent
console.log(0 === '') // false, not exactly the same
console.log(0 === false) // false, not exactly the same
console.log(1 == true) // true, equivalent
console.log(1 === true) // false, not exactly the same
console.log(undefined == null) // true
@ -210,13 +211,13 @@ console.log(typeof NaN) // number
console.log('mango'.length == 'avocado'.length) // false
console.log('mango'.length != 'avocado'.length) // true
console.log('mango'.length < 'avocado'.length) // true
console.log('milk'.length != 'meat'.length) // false
console.log('milk'.length == 'meat'.length) // true
console.log('milk'.length != 'meat'.length) // false
console.log('tomato'.length == 'potato'.length) // true
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. Remembering 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.
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.
@ -225,30 +226,30 @@ As rule of thumb, if a value is not true with == it will not be equal with ===.
The following symbols are the common logical operators:
&&(ampersand) , ||(pipe) and !(negation).
&& gets true only if the two operands are true.
|| gets true either of the operand is true.
! negates true to false, false to true.
The && operator gets true only if the two operands are true.
The || operator gets true either of the operand is true.
The ! operator negates true to false and false to true.
```js
//&& ampersand operator example
// && ampersand operator example
const check = 4 > 3 && 10 > 5 // true and true -> true
const check = 4 > 3 && 10 < 5 // true and false -> false
const check = 4 < 3 && 10 < 5 // false and false -> false
const check = 4 > 3 && 10 > 5 // true && true -> true
const check = 4 > 3 && 10 < 5 // true && false -> false
const check = 4 < 3 && 10 < 5 // false && false -> false
//|| pipe or operator, example
// || pipe or operator, example
const check = 4 > 3 || 10 > 5 // true and true -> true
const check = 4 > 3 || 10 < 5 // true and false -> true
const check = 4 < 3 || 10 < 5 // false and false -> false
const check = 4 > 3 || 10 > 5 // true || true -> true
const check = 4 > 3 || 10 < 5 // true || false -> true
const check = 4 < 3 || 10 < 5 // false || false -> false
//! Negation examples
let check = 4 > 3 // true
let check = !(4 > 3) // false
let check = 4 > 3 // true
let check = !(4 > 3) // false
let isLightOn = true
let isLightOff = !isLightOn // false
let isMarried = !false // true
let isLightOff = !isLightOn // false
let isMarried = !false // true
```
### Increment Operator
@ -259,16 +260,16 @@ In JavaScrip we use the increment operator to increase a value stored in a varia
```js
let count = 0
console.log(++count) // 1
console.log(count) // 1
console.log(++count) // 1
console.log(count) // 1
```
1. Post-increment
```js
let count = 0
console.log(count++) // 0
console.log(count) // 1
console.log(count++) // 0
console.log(count) // 1
```
We use most of the time post-increment. At leas you should remember how to use post-increment operator.
@ -350,7 +351,7 @@ alert(message)
alert('Welcome to 30DaysOfJavaScript')
```
Do not use too much alert because it is destructing and annoying, use it just for to test.
Do not use too much alert because it is destructing and annoying, use it just to test.
### Window prompt() method
@ -368,8 +369,8 @@ console.log(number)
### Window confirm() method
The confirm() method displays a dialog box with a specified message, along with an OK and a Cancel button.
A confirm box is often used to ask permission from a user to do something. Window confirm() takes an string as an argument.
Clicking the OK yields true value, clicking the Cancel button yields false value.
A confirm box is often used to ask permission from a user to execute something. Window confirm() takes a string as an argument.
Clicking the OK yields true value, whereas clicking the Cancel button yields false value.
```js
const agree = confirm('Are you sure you like to delete? ')
@ -398,7 +399,7 @@ We have created a time object and we can access any date time information from t
### Getting full year
Let's extract or get the full from a time object.
Let's extract or get the full year from a time object.
```js
const now = new Date()
@ -420,7 +421,7 @@ Let's extract or get the date of the month from a time object.
```js
const now = new Date()
console.log(now.getDate()) // 4, because the day of the month is 4th, day(0-31)
console.log(now.getDate()) // 4, because the day of the month is 4th, day(1-31)
```
### Getting day
@ -429,7 +430,8 @@ Let's extract or get the day of the week from a time object.
```js
const now = new Date()
console.log(now.getDay()) // 6, because the day is Saturday which is the 5th day,
console.log(now.getDay()) // 6, because the day is Saturday which is the 7th day
// Sunday is 0, Monday is 1 and Saturday is 6
// Getting the weekday as a number (0-6)
```
@ -476,6 +478,7 @@ console.log(now.getTime()) // 1578092201341, this is the number of seconds passe
```js
const allSeconds = Date.now() //
console.log(allSeconds) // 1578092201341, this is the number of seconds passed from January 1, 1970 to January 4, 2020 00:56:41
const timeInSeconds = new Date().getTime()
console.log(allSeconds == timeInSeconds) // true
```
@ -490,21 +493,60 @@ const month = now.getMonth() + 1 // return month(0 - 11)
const date = now.getDate() // return date (1 - 31)
const hours = now.getHours() // return number (0 - 23)
const minutes = now.getMinutes() // return number (0 -59)
console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
```
🌕 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.
🌕 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
### Exercises: Level 1
# 💻 Day 3: Exercises
1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it and use the typeof operator to check different data types.
2. Check if type of '10' is equal to 10
3. Check if parseInt('9.8') is equal to 10
4. Boolean value is either true or false.
1. Write three JavaScript statement which provide truthy value.
2. Write three JavaScript statement which provide falsy value.
## 1. Exercises: Data types Part
5. Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log()
1. 4 > 3
2. 4 >= 3
3. 4 < 3
4. 4 <= 3
5. 4 == 4
6. 4 === 4
7. 4 != 4
8. 4 !== 4
9. 4 != '4'
10. 4 == '4'
11. 4 === '4'
12. Find the length of python and jargon and make a falsy comparison statement.
6. Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log()
1. 4 > 3 && 10 < 12
2. 4 > 3 && 10 > 12
3. 4 > 3 || 10 < 12
4. 4 > 3 || 10 > 12
5. !(4 > 3)
6. !(4 < 3)
7. !(false)
8. !(4 > 3 && 10 < 12)
9. !(4 > 3 && 10 > 12)
10. !(4 === '4')
11. There is no 'on' in both dragon and python
1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it
1. The JavaScript typeof operator uses to check different data types. Check the data type of each variables from question number 1.
1. Check if type of '10' is equal to 10
1. Check if parseInt('9.8') is equal to 10
7. Use the Date object to do the following activities
1. What is the year today?
2. What is the month today as a number?
3. What is the date today?
4. What is the day today as a number?
5. What is the hours now?
6. What is the minutes now?
7. Find out the numbers of seconds elapsed from January 1, 1970 to now.
## 2. Exercises: Arithmetic Operators Part
### Exercises: Level 2
1. Write a script that prompt the user to enter base and height of the triangle and calculate an area of a triangle (area = 0.5 x b x h).
@ -531,75 +573,25 @@ console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
1. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is 0.
1. Writ a script that prompt a user to enters hours and rate per hour. Calculate pay of the person?
```sh
Enter hours: 40
Enter rate per hour: 28
Your weekly earning is 1120
```
1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years
```sh
Enter number of yours you live: 100
You lived 3153600000 seconds.
```
## 3. Exercises: Booleans Part
Boolean value is either true or false.
1. Write three JavaScript statement which provide truthy value.
1. Write three JavaScript statement which provide falsy value.
## 4. Exercises: Comparison Operators
Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log()
1. 4 > 3
1. 4 >= 3
1. 4 < 3
1. 4 <= 3
1. 4 == 4
1. 4 === 4
1. 4 != 4
1. 4 !== 4
1. 4 != '4'
1. 4 == '4'
1. 4 === '4'
Find the length of python and jargon and make a falsy comparison statement.
## 5. Exercises: Logical Operators
1. Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log()
1. 4 > 3 && 10 < 12
2. 4 > 3 && 10 > 12
3. 4 > 3 || 10 < 12
4. 4 > 3 || 10 > 12
5. !(4 > 3)
6. !(4 < 3)
7. !(false)
8. !(4 > 3 && 10 < 12)
9. !(4 > 3 && 10 > 12)
10. !(4 === '4')
2. There is no 'on' in both dragon and python
## 6 Ternary Operator
```sh
Enter hours: 40
Enter rate per hour: 28
Your weekly earning is 1120
```
1. If the length of your name is greater than 7 say, your name is long else say your name is short.
1. Compare your first name length and your family name length and you should get this output.
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
```
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
```
```sh
//Output
Your first name, Asabeneh is longer than your family name, Yetayeh
```
```sh
Your first name, Asabeneh is longer than your family name, Yetayeh
```
1. Declare two variables _myAge_ and _yourAge_ and assign them initial values and myAge and yourAge.
Output:
```js
let myAge = 250
@ -607,33 +599,35 @@ Your first name, Asabeneh is longer than your family name, Yetayeh
```
```sh
//output
I am 225 years older than you.
```
1. Using prompt get the year the user was born and if the user is 18 or above allow the user to drive if not tell the user to wait a certain amount of years.
```sh
// if the age is 25
You are 25. You are old enough to drive
// if the age is under 18
You are 15. You will be allowed to drive after 3 years.
```
```sh
Enter birth year: 1995
You are 25. You are old enough to drive
Enter birth year: 2005
You are 15. You will be allowed to drive after 3 years.
```
1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years
```sh
Enter number of yours you live: 100
You lived 3153600000 seconds.
```
## 7. Exercises: Date time Object
1. Create a human readable time format using the Date time object
1. YYYY-MM-DD HH:mm
2. DD-MM-YYYY HH:mm
3. DD/MM/YYYY HH:mm
1. What is the year today?
1. What is the month today as a number?
1. What is the date today?
1. What is the day today as a number?
1. What is the hours now?
1. What is the minutes now?
1. Find out the numbers of seconds elapsed from January 1, 1970 to now.
1. Create a human readable time format
1. YYY-MM-DD HH:mm:ss
2. DD-MM-YYYY HH:mm:ss
3. DD/MM/YYY HH:mm:ss
### Exercises: Level 3
🎉 CONGRATULATIONS ! 🎉
1. Create a human readable time format using the Date time object. The hour and the minute should be all the time two digits(7 hours should be 07 and 5 minutes should be 05 )
1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05
[<< 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](../02_Day_Data_types/02_day_data_types.md) | [Day 4 >>](../04_Day_Conditionals/04_day_conditionals.md)

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Conditionals</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>
@ -13,24 +13,27 @@
</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](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) | [Day 5 >>](../05_Day_Arrays/05_day_arrays.md)
![Thirty Days Of JavaScript](../images/banners/day_1_4.png)
- [📔 Day 4](#%f0%9f%93%94-day-4)
- [📔 Day 4](#-day-4)
- [Conditionals](#conditionals)
- [if](#if)
- [if else](#if-else)
- [if else if else](#if-else-if-else)
- [Switch](#switch)
- [Ternary Operators](#ternary-operators)
- [💻 Exercise : Conditionals](#%f0%9f%92%bb-exercise--conditionals)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 4
## Conditionals
Conditional statements are used to decision based on different conditions.
Conditional statements are used to make decisions based on different conditions.
By default , statements in JavaScript script executed sequentially from top to bottom. If the processing logic require so, the sequential flow of execution can be altered in two ways:
- Conditional execution: a block of one or more statements will be executed if a certain expression is true
@ -46,7 +49,7 @@ Conditions can be implementing using the following ways:
### if
In JavaScript and other programming languages the key word _if_ use to check if a condition is true and to execute the block code. To create an if condition, we need _if_ keyword, condition inside a parenthesis and block of code inside a curly bracket({}).
In JavaScript and other programming languages the key word _if_ is used to check if a condition is true and to execute the block code. To create an if condition, we need _if_ keyword, condition inside a parenthesis and block of code inside a curly bracket({}).
```js
// syntax
@ -65,6 +68,8 @@ if (num > 0) {
// 3 is a positive number
```
As you can see in the above condition, 3 is greater than 0 and it is a positive number. The condition was true and the block code was executed. However, if the condition is false, we do not see a result.
```js
let isRaining = true
if (isRaining) {
@ -72,7 +77,7 @@ if (isRaining) {
}
```
As you can see in the above condition, 3 is greater than 0 and it is a positive number. The condition was true and the block code was executed. However, if the condition is false, we do not see a result. The same goes for the second condition, if isRaining is false the if block will not be executed and we do not see an output. In order to see the result of the falsy condition, we should have another block, which is going to be _else_.
The same goes for the second condition, if isRaining is false the if block will not be executed and we do not see an output. In order to see the result of the falsy condition, we should have another block, which is going to be _else_.
### if else
@ -127,7 +132,7 @@ The above condition is false, therefore the else block was executed. How about i
### 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 of conditions. We use *else if* when we have multiple conditions.
```js
// syntax
@ -238,6 +243,25 @@ switch (day) {
```
// Examples to use conditions in the cases
```js
let num = prompt('Enter number');
switch (true) {
case num > 0:
console.log('Number is positive');
break;
case num == 0:
console.log('Numbers is zero');
break;
case num < 0:
console.log('Number is negative');
break;
default:
console.log('Entered value was not a number');
}
```
### Ternary Operators
Another way to write conditionals is using ternary operators. We have covered this in other sections but we should also mention it here.
@ -251,7 +275,9 @@ isRaining
🌕 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
## 💻 Exercises
### Exercises: Level 1
1. Get user input using prompt(“Enter your age:”). If user is 18 or older , give feedback:You are old enough to drive but if not 18 give feedback to wait for the years he supposed to wait for.
@ -284,19 +310,6 @@ isRaining
4 is greater than 3
```
1. Write a code which give grade students according to theirs scores:
- 80-100, A
- 70-89, B
- 60-69, C
- 50-59, D
- 0 -49, F
1. Check if the season is Autumn, Winter, Spring or Summer.
If the user input is:
- September, October or November, the season is Autumn.
- December, January or February, the season is Winter.
- March, April or May, the season is Spring
- June, July or August, the season is Summer
1. Even numbers are divisible by 2 and the remainder is zero. How do you check if a number is even or not using JavaScript?
```sh
@ -307,39 +320,54 @@ isRaining
9 is is an odd number.
```
### Exercises: Level 2
1. Write a code which can give grade to students according to theirs scores:
- 80-100, A
- 70-89, B
- 60-69, C
- 50-59, D
- 0-49, F
1. Check if the season is Autumn, Winter, Spring or Summer.
If the user input is:
- September, October or November, the season is Autumn.
- December, January or February, the season is Winter.
- March, April or May, the season is Spring
- June, July or August, the season is Summer
1. Check if a day is weekend day or a working day. Your script will take day as an input.
```sh
What is the day is today? Saturday
Saturday is a weekend day.
What is the day today? Saturday
Saturday is a weekend.
What is the day today? saturDaY
Saturday is a weekend day.
Saturday is a weekend.
What is the day today? Friday
Friday is a work day.
Friday is a working day.
What is the day today? FrIDAy
Friday is a work day.
Friday is a working day.
```
1. Write a program which tells the number days in a month.
### Exercises: Level 3
1. Write a program which tells the number of days in a month.
```sh
Enter month: January
Enter a month: January
January has 31 days.
Enter month: JANUARY
Enter a month: JANUARY
January has 31 day
Enter month: February
Enter a month: February
February has 28 days.
Enter month: FEbruary
Enter a month: FEbruary
February has 28 days.
```
🎉 CONGRATULATIONS ! 🎉
[<< 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](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) | [Day 5 >>](../05_Day_Arrays/05_day_arrays.md)

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Arrays</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>
@ -13,11 +13,11 @@
</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](../04_Day_Conditionals/04_day_Conditionals.md) | [Day 6 >>](../06_Day_Loops/06_day_loops.md)
![Day 5](../images/banners/day_1_5.png)
- [📔 Day 5](#%f0%9f%93%94-day-5)
- [📔 Day 5](#-day-5)
- [Arrays](#arrays)
- [How to create an empty array](#how-to-create-an-empty-array)
- [How to create an array with values](#how-to-create-an-array-with-values)
@ -43,20 +43,23 @@
- [Reversing array order](#reversing-array-order)
- [Sorting elements in array](#sorting-elements-in-array)
- [Array of arrays](#array-of-arrays)
- [💻 Exercise](#%f0%9f%92%bb-exercise)
- [💻 Exercise](#-exercise)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
# 📔 Day 5
## Arrays
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.
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 index of the last element is less by one from the length of the array.
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
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.
In JavaScript, we can create an array in different ways. Let us see 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 variable name again.
- Using Array constructor
@ -163,7 +166,7 @@ console.log(words)
### Accessing array items using 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.
We access each element in an array using their index. An array index starts from 0. The picture below clearly shows the index of each element in the array.
![arr index](../images/array_index.png)
@ -328,7 +331,7 @@ const eight0values = Array(8).fill(0) // it creates eight element values filled
console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0]
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]
```
#### Concatenating array using concat
@ -471,7 +474,7 @@ console.log(names.toString()) // Asabeneh,Mathias,Elias,Brook
#### Joining array elements
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.
join: It is used to join the elements of the array, the argument we 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
const numbers = [1, 2, 3, 4, 5]
@ -529,8 +532,8 @@ Splice: It takes three parameters:Starting position, number of times to be remov
```
```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
const numbers = [1, 2, 3, 4, 5, 6];
console.log(numbers.splice(3, 3, 7, 8, 9)) // -> [1, 2, 3, 7, 8, 9] //it removes three item and replace three items
```
#### Adding item to an array using push
@ -615,7 +618,7 @@ console.log(numbers) // [1, 2, 3, 4, 5]
#### Sorting elements in array
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.
sort: arrange array elements in ascending order. Sort takes a call back function, we will see how we use sort with a call back function in the coming sections.
```js
const webTechs = [
@ -659,6 +662,8 @@ console.log(arrayOfArray[0]) // [1, 2, 3]
## 💻 Exercise
### Exercise: Level 1
```js
const countries = [
'Albania',
@ -686,30 +691,33 @@ const webTechs = [
```
1. Declare an _empty_ array;
1. Declare an array with more than 5 number of elements
1. Find the length of your array
1. Get the first item, the middle item and the last item of the array
1. Declare an array called _mixedDataTypes_,put different data types in your array and find length of the array. You are should size be greater than 5
1. Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon
1. Print the array using _console.log()_
1. Print the number of companies in the array
1. Print the first company, middle and last company
1. Print out each company
1. Change each company name to uppercase one by one and print them out
1. Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies.
1. Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is _not found_
1. Filter out companies which have more than one 'o' without the filter method
1. Sort the array using _sort()_ method
1. Reverse the array using _reverse()_ method
1. Slice out the first 3 companies from the array
1. Slice out the last 3 companies from the array
1. Slice out the middle IT company or companies from the array
1. Remove the first IT company from the array
1. Remove the middle IT company or companies from the array
1. Remove the last IT company from the array
1. Remove all IT companies
1. Create a separate countries.js file and store the countries array in to this file, create a separate file web_techs.js ans store the webTechs array in to this file. Access both file in main.js file
1. First remove all the functions and change the string to array and count the number of words in the array
2. Declare an array with more than 5 number of elements
3. Find the length of your array
4. Get the first item, the middle item and the last item of the array
5. Declare an array called _mixedDataTypes_, put different data types in the array and find the length of the array. The array size should be greater than 5
6. Declare an array variable name itCompanies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon
7. Print the array using _console.log()_
8. Print the number of companies in the array
9. Print the first company, middle and last company
10. Print out each company
11. Change each company name to uppercase one by one and print them out
12. Print the array like as a sentence: Facebook, Google, Microsoft, Apple, IBM,Oracle and Amazon are big IT companies.
13. Check if a certain company exists in the itCompanies array. If it exist return the company else return a company is _not found_
14. Filter out companies which have more than one 'o' without the filter method
15. Sort the array using _sort()_ method
16. Reverse the array using _reverse()_ method
17. Slice out the first 3 companies from the array
18. Slice out the last 3 companies from the array
19. Slice out the middle IT company or companies from the array
20. Remove the first IT company from the array
21. Remove the middle IT company or companies from the array
22. Remove the last IT company from the array
23. Remove all IT companies
### Exercise: Level 2
1. Create a separate countries.js file and store the countries array in to this file, create a separate file web_techs.js and store the webTechs array in to this file. Access both file in main.js file
1. First remove all the punctuations and change the string to array and count the number of words in the array
```js
let text =
@ -720,6 +728,7 @@ const webTechs = [
```sh
["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"]
13
```
@ -729,10 +738,10 @@ const webTechs = [
const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey']
```
- add 'Meat' in the beginning of your shopping cart if if it has not be already added
- add sugar at the end of you shopping cart if it has not been already added
- Remove 'Honey' if you are allergic to honey
- modify tea to 'Green Tea'
- add 'Meat' in the beginning of your shopping cart if it has not been already added
- add Sugar at the end of you shopping cart if it has not been already added
- remove 'Honey' if you are allergic to honey
- 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 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.
@ -748,6 +757,8 @@ const webTechs = [
["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]
```
### Exercise: Level 3
1. The following is an array of 10 students ages:
```js
@ -755,16 +766,14 @@ const webTechs = [
```
- Sort the array and find the min and max age
- Find the min age and the max age
- Find the median age(one middle item or two middle items divided by two)
- Find the average age(all items divided by number of items)
- Find the range of the ages(max minus min)
- Compare the value of (min - average) and (max - average), use *abs()* method
1.Slice the first ten countries from 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. 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.
2. 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 ! 🎉
[<< 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](../04_Day_Conditionals/04_day_Conditionals.md) | [Day 6 >>](../06_Day_Loops/06_day_loops.md)

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Loops</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>
@ -13,11 +13,11 @@
</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](../05_Day_Arrays/05_day_arrays.md) | [Day 7 >>](../07_Day_Functions/07_day_functions.md)
![Day 5](../images/banners/day_1_6.png)
- [📔 Day 6](#%f0%9f%93%94-day-6)
- [📔 Day 6](#-day-6)
- [Loops](#loops)
- [for Loop](#for-loop)
- [while loop](#while-loop)
@ -25,20 +25,23 @@
- [for of loop](#for-of-loop)
- [break](#break)
- [continue](#continue)
- [💻 Exercises:Day 6](#%f0%9f%92%bb-exercisesday-6)
- [💻 Exercises:Day 6](#-exercisesday-6)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 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.
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. If you prefer watching the videos, you can checkout the [video tutorials](https://www.youtube.com/channel/UCM4xOopkYiPwJqyKsSqL9mw)
In programming languages to carry out repetitive task we use different kinds of loop. The following examples are the commonly used loops.
In programming languages to carry out repetitive task we use different kinds of loops. The following examples are the commonly used loops in JavaScript and other programming languages.
### for Loop
```js
//For loop structure
// For loop structure
for(initialization, condition, increment/decrement){
// code goes here
}
@ -48,6 +51,7 @@ for(initialization, condition, increment/decrement){
for(let i = 0; i <= 5; i++){
console.log(i)
}
// 0 1 2 3 4 5
```
@ -55,7 +59,8 @@ for(let i = 0; i <= 5; i++){
for(let i = 5; i >= 0; i--){
console.log(i)
}
// 5 4 3 2 1 0
// 5 4 3 2 1 0
```
```js
@ -79,7 +84,8 @@ const newArr = []
for(let i = 0; i < countries.length; i++){
newArr.push(countries[i].toUpperCase())
}
//["FINLAND", "SWEDEN", "DENMARK", "NORWAY", "ICELAND"]
// ["FINLAND", "SWEDEN", "DENMARK", "NORWAY", "ICELAND"]
```
Adding all elements in the array
@ -127,6 +133,7 @@ while (i <= 5) {
console.log(i)
i++
}
// 0 1 2 3 4 5
```
@ -138,12 +145,13 @@ 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.
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 of each element in the array.
```js
for (const element of arr) {
@ -156,13 +164,17 @@ for (const element of arr) {
const numbers = [1, 2, 3, 4, 5]
for (const num of numbers) {
console.log(num) //1 2 3 4 5
console.log(num)
}
// 1 2 3 4 5
for (const num of numbers) {
console.log(num * num) //1 4 9 16 25
console.log(num * num)
}
// 1 4 9 16 25
// adding all the numbers in the array
let sum = 0
for (const num of numbers) {
@ -170,8 +182,6 @@ for (const num of numbers) {
}
console.log(sum) // 15
const webTechs = [
'HTML',
'CSS',
@ -183,11 +193,13 @@ const webTechs = [
]
for (const tech of webTechs) {
console.log(tech.toUpperCase()) // HTML CSS JAVASCRIPT REACT NODE MONGODB
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
console.log(tech[0]) // get only the first letter of each element, H C J R N M
}
```
@ -204,16 +216,42 @@ console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
### break
content will be added soon
Break is used to interrupt a loop.
```js
for(let i = 0; i <= 5; i++){
if(i == 3){
break
}
console.log(i)
}
// 0 1 2
```
The above code stops if 3 found in the iteration process.
### continue
content will added soon
We use the keyword *continue* to skip a certain iterations.
```js
for(let i = 0; i <= 5; i++){
if(i == 3){
continue
}
console.log(i)
}
// 0 1 2 4 5
```
🌕 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
### Exercises: Level 1
```js
const countries = [
'Albania',
@ -293,16 +331,16 @@ content will added soon
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.
10. Use for loop to iterate from 0 to 100 and print the sum of all numbers.
```sh
The sum all numbers is 5050.
The sum of all numbers from 0 to 100 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.
The sum of all evens from 0 to 100 is 2550. And the sum of all odds from 0 to 100 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
@ -319,7 +357,9 @@ content will added soon
5j2khz
```
16. Develop a small script which generate any number of characters random id:
### Exercises: Level 2
1. Develop a small script which generate any number of characters random id:
```sh
fe3jo1gl124g
@ -329,31 +369,31 @@ content will added soon
xkqci4utda1lmbelpkm03rba
```
17. Write a script which generates a random hexadecimal number.
1. Write a script which generates a random hexadecimal number.
```sh
'#ee33df'
```
18. Write a script which generates a random rgb color number.
1. 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.
1. 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'.
1. 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:
1. Use the countries array to create the following array of arrays:
```sh
[
@ -371,42 +411,41 @@ content will added soon
]
```
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'.
2. 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 'All these countries are 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'.
3. In above countries array, check if there is 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 'ai', 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.
4. 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.
5. 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:
6. Find the longest word in the webTechs array
7. Use the webTechs array 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.
8. An application created using MongoDB, Express, React and Node is called a MERN stack app. Create the acronym MERN by using the array mernStack
9. 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.
10. This is a fruit array , ['banana', 'orange', 'mango', 'lemon'] reverse the order using loop without using a reverse method.
11. Print all the elements of array as shown below.
```js
const fullStack = [
@ -424,16 +463,19 @@ content will added soon
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
### Exercises: Level 3
1. Copy countries array(Avoid mutation)
1. Arrays are mutable. Create a copy of array which does not modify the original. Sort the copied array and store in a variable sortedCountries
1. Sort the webTechs array and mernStack array
1. 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
1. Find the country containing the hightest number of characters in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. 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
1. 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
1. 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
1. 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)
[<< Day 5](../05_Day_Arrays/05_day_arrays.md) | [Day 7 >>](../07_Day_Functions/07_day_functions.md)

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Functions</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>
@ -13,11 +13,11 @@
</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)
[<< Day 6](../06_Day_Loops/06_day_loops.md) | [Day 8 >>](../08_Day_Objects/08_day_objects.md)
![Thirty Days Of JavaScript](../images/banners/day_1_7.png)
- [📔 Day 7](#%f0%9f%93%94-day-7)
- [📔 Day 7](#-day-7)
- [Functions](#functions)
- [Function Declaration](#function-declaration)
- [Function without a parameter and return](#function-without-a-parameter-and-return)
@ -34,7 +34,10 @@
- [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)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 7
@ -76,12 +79,13 @@ Function can be declared without a parameter.
**Example:**
```js
// function without parameter, a function which square a number
// function without parameter, a function which make a number square
function square() {
let num = 2
let sq = num * num
console.log(sq)
}
square() // 4
// function without parameter
@ -92,18 +96,20 @@ function addTwoNumbers() {
console.log(sum)
}
addTwoNumbers() // function has to be called to be executed by it name
addTwoNumbers() // a function has to be called by its name to be executed
```
```js
function generateFullName (){
function printFullName (){
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let space = ' '
let fullName = firstName + space + lastName
console.log(fullName)
}
generateFullName() // calling a function
printFullName() // calling a function
```
### Function returning value
@ -111,14 +117,14 @@ addTwoNumbers() // function has to be called to be executed by it name
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 (){
function printFullName (){
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(generateFullName())
console.log(printFullName())
```
```js
@ -167,19 +173,20 @@ 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 without parameter doesn't take input, so lets make a function with parameters
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) {
function sumTwoNumbers(numOne, numTwo) {
let sum = numOne + numTwo
return sum
}
console.log(sumTwoNumbersAndReturn(10, 20))
console.log(sumTwoNumbers(10, 20))
function printFullName(firstName, lastName) {
return `${firstName} ${lastName}`
}
@ -200,7 +207,7 @@ functionName(parm1,parm2,parm3,...) // during calling or invoking three argument
function sumArrayValues(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum = sum + numbers[i];
sum = sum + arr[i];
}
return sum;
}
@ -219,7 +226,7 @@ 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.
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
@ -301,15 +308,9 @@ const anonymousFun = function() {
### 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.
Expression functions are anonymous functions. After we create a function without a name and we 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) {
@ -339,7 +340,7 @@ console.log(squaredNum)
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.
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
@ -354,9 +355,10 @@ 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
console.log(square(2)) // -> 4
// if we have only one line in the code block, it can be written as follows, explicit return
const square = n => n * n // -> 4
```
```js
@ -500,10 +502,14 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
### Function declaration versus Arrow function
It ill be covered in other time
🌕 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
### Exercises: Level 1
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.
@ -533,9 +539,11 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
console.log(findMax(0, -10, -2))
0
```
### Exercises: Level 2
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_.
1. Linear equation is calculated as follows: _ax + by + c = 0_. Write a function which calculates value of a linear equation, _solveLinEquation_.
1. 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}
@ -546,22 +554,22 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
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.
1. Declare a function name _printArray_. It takes array as a parameter and it prints out each value of the array.
1. 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.
1. 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).
1. 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]))
@ -570,13 +578,13 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
//['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.
1. Declare a function name _capitalizeArray_. It takes array as a parameter and it returns the - capitalizedarray.
1. Declare a function name _addItem_. It takes an item parameter and it returns an array after adding the item
1. Declare a function name _removeItem_. It takes an index parameter and it returns an array after removing an item
1. Declare a function name _sumOfNumbers_. It takes a number parameter and it adds all the numbers in that range.
1. Declare a function name _sumOfOdds_. It takes a number parameter and it adds all the odd numbers in that - range.
1. Declare a function name _sumOfEven_. It takes a number parameter and it adds all the even numbers in that - range.
1. 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);
@ -584,30 +592,32 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
The number of evens are 51.
```
29. Write a function which takes any number of arguments and return the sum of the arguments
1. 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.
1. Writ a function which generates a _randomUserIp_.
1. Write a function which generates a _randomMacAddress_
1. 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.
1. 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.
### Exercises: Level 3
1. 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()
@ -626,18 +636,18 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
'
```
35. Write a function name _rgbColorGenerator_ and it generates rgb colors.
1. 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.
1. Write a function **_arrayOfHexaColors_** which return any number of hexadecimal colors in an array.
1. Write a function **_arrayOfRgbColors_** which return any number of RGB colors in an array.
1. Write a function **_convertHexaToRgb_** which converts hexa color to rgb and it returns an rgb color.
1. Write a function **_convertRgbToHexa_** which converts rgb to hexa color and it returns an hexa color.
1. Write a function **_generateColors_** which can generate any number of hexa or rgb colors.
```js
console.log(generateColors('hexa', 3)) // ['#a3e12f', '#03ed55', '#eb3d2b']
@ -646,35 +656,51 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
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'.
1. Call your function _shuffleArray_, it takes an array as a parameter and it returns a shuffled array
1. Call your function _factorial_, it takes a whole number as a parameter and it return a factorial of the number
1. Call your function _isEmpty_, it takes a parameter and it checks if it is empty or not
1. Call your function _sum_, it takes any number of arguments and it returns the sum.
1. 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.
1. 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.
1. 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']
```
```sh
['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']
```
```js
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon','Microsoft', 'IBM']);
// →['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM']
```
```sh
['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM']
```
```js
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.
```sh
'Not Found'
```
1. Write a function called _isPrime_, which checks if a number is prime number.
1. Write a functions which checks if all items are unique in the array.
1. Write a function which checks if all the items of the array are the same data type.
1. 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.
1. 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)]
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
1. 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)
[<< Day 6](../06_Day_Loops/06_day_loops.md) | [Day 8 >>](../08_Day_Objects/08_day_objects.md)

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Objects</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>
@ -13,16 +13,16 @@
</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)
[<< Day 7](../07_Day_Functions/07_day_functions.md) | [Day 9 >>](../09_Day_Higher_order_functions/09_day_higher_order_functions.md)
![Thirty Days Of JavaScript](../images/banners/day_1_8.png)
- [📔 Day 8](#%f0%9f%93%94-day-8)
- [📔 Day 8](#-day-8)
- [Scope](#scope)
- [Window Scope](#window-scope)
- [Global scope](#global-scope)
- [Local scope](#local-scope)
- [📔 Object](#%f0%9f%93%94-object)
- [📔 Object](#-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)
@ -33,7 +33,10 @@
- [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)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 8
@ -70,7 +73,7 @@ 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.
A globally declared variable can be accessed 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
@ -91,7 +94,7 @@ console.log(a, b) // JavaScript 10, accessible
### Local scope
A local declared variable can be access only certain block code.
A variable declared as local can be accessed only in certain block code.
```js
//scope.js
@ -115,7 +118,7 @@ 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)
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). Block in JavaScript is a code in between two curly brackets ({}).
```js
//scope.js
@ -139,7 +142,7 @@ 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.
In ES6 and above there is *let* and *const*, so you will not suffer from the sneakiness of *var*. When we use *let* our variable is block scoped and it will not infect other parts of our code.
```js
//scope.js
@ -164,12 +167,12 @@ for(let i = 0; i < 3; i++){
```
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.
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, and for 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.
Everything can be an object and objects do have properties and properties have values, so an object is a key value pair. The order of the key is not reserved, or there is no order.
To create an object literal, we use two curly brackets.
### Creating an empty object
@ -183,7 +186,7 @@ const person = {}
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.
Let us see some examples of object. Each key has a value in the object.
```js
const rectangle = {
@ -365,7 +368,7 @@ const person = {
city: 'Helsinki'
},
getPersonInfo: function() {
return `I am ${this.firstName} and I live in ${city}, ${this.country}. I am ${this.age}.`
return `I am ${this.firstName} and I live in ${this.city}, ${this.country}. I am ${this.age}.`
}
}
@ -414,16 +417,21 @@ 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.
🌕 You are astonishing. Now, you are super charged with the power of objects. You have just completed day 8 challenges and you are 8 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises
### Exercises: Level 1
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.
### Exercises: Level 2
1. Find the person who has many skills in the users object.
1. Count logged in users,count users having greater than equal to 50 points from the following object.
````js
@ -479,15 +487,103 @@ console.log(copyPerson.hasOwnProperty('score'))
}
}```
````
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.
### Exercises: Level 3
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.
2. **** Questions:2, 3 and 4 are based on the following two arrays:users and products ()
```js
const users = [
{
_id: 'ab12ex',
username: 'Alex',
email: 'alex@alex.com',
password: '123123',
createdAt:'08/01/2020 9:00 AM',
isLoggedIn: false
},
{
_id: 'fg12cy',
username: 'Asab',
email: 'asab@asab.com',
password: '123456',
createdAt:'08/01/2020 9:30 AM',
isLoggedIn: true
},
{
_id: 'zwf8md',
username: 'Brook',
email: 'brook@brook.com',
password: '123111',
createdAt:'08/01/2020 9:45 AM',
isLoggedIn: true
},
{
_id: 'eefamr',
username: 'Martha',
email: 'martha@martha.com',
password: '123222',
createdAt:'08/01/2020 9:50 AM',
isLoggedIn: false
},
{
_id: 'ghderc',
username: 'Thomas',
email: 'thomas@thomas.com',
password: '123333',
createdAt:'08/01/2020 10:00 AM',
isLoggedIn: false
}
];
const products = [
{
_id: 'eedfcf',
name: 'mobile phone',
description: 'Huawei Honor',
price: 200,
ratings: [
{ userId: 'fg12cy', rate: 5 },
{ userId: 'zwf8md', rate: 4.5 }
],
likes: []
},
{
_id: 'aegfal',
name: 'Laptop',
description: 'MacPro: System Darwin',
price: 2500,
ratings: [],
likes: ['fg12cy']
},
{
_id: 'hedfcg',
name: 'TV',
description: 'Smart TV:Procaster',
price: 400,
ratings: [{ userId: 'fg12cy', rate: 5 }],
likes: ['fg12cy']
}
]
```
Imagine you are getting the above users collection from a MongoDB database.
a. Create a function called signUp which allows user to add to the collection. If user exists, inform the user that he has already an account.
b. Create a function called signIn which allows user to sign in to the application
3. The products array has three elements and each of them has six properties.
a. Create a function called rateProduct which rates the product
b. Create a function called averageRating which calculate the average rating of a product
4. Create a function called likeProduct. This function will helps to like to the product if it is not liked and remove like if it was liked.
🎉 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)
[<< Day 7](../07_Day_Functions/07_day_functions.md) | [Day 9 >>](../09_Day_Higher_order_functions/09_day_higher_order_functions.md)

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Higher Order Functions</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>
@ -13,7 +13,7 @@
</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 8](../08_Day_Objects/08_day_objects.md) | [Day 10 >>](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md)
![Day 5](../images/banners/day_1_9.png)
@ -37,7 +37,10 @@
- [Sorting string values](#sorting-string-values)
- [Sorting Numeric values](#sorting-numeric-values)
- [Sorting Object Arrays](#sorting-object-arrays)
- [💻 Exercises](#%f0%9f%92%bb-exercises)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 9
@ -553,6 +556,8 @@ console.log(users) // sorted ascending
## 💻 Exercises
### Exercises: Level 1
```js
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
@ -582,8 +587,6 @@ const products = [
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_**
@ -595,13 +598,21 @@ const products = [
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:
### Exercises: Level 2
1. Find the total price of products by chaining two or more array iterators(eg. arr.map(callback).filter(callback).reduce(callback))
1. Find the sum of price of products using only reduce reduce(callback))
1. 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')).
1. 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.
1. Declare a **_getFirstTenCountries_** function and return an array of ten countries. Use different functional programming to work on the countries.js array
1. Declare a **_getLastTenCountries_** function which which returns the last ten countries in the countries array.
1. Find out which _letter_ is used many _times_ as initial for a country name from the countries array (eg. Finland, Fiji, France etc)
### Exercises: Level 3
1. Use the countries information, in the data folder. Sort countries by name, by capital, by population
1. \*\*\* Find the 10 most spoken languages:
````js
// Your output should look like this
@ -628,67 +639,66 @@ const products = [
````
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.
1. \*\*\* Use countries_data.js file create a function which create the ten most populated countries
```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)]
```
````js
console.log(mostPopulatedCountries(countries, 10))
```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)]
```
[
{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}
]
```
1. \*\*\* 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)
[<< Day 8](../08_Day_Objects/08_day_objects.md) | [Day 10 >>](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md)

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Sets and Maps</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>
@ -13,9 +13,9 @@
</sub>
</div>
[<< Day 9](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md) | [Day 11>>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/11_Day/11_destructuring_and_spreading.md)
[<< Day 9](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) | [Day 11>>](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md)
![Day 5](../images/banners/day_1_10.png)
![Day 10](../images/banners/day_1_10.png)
- [Day 10](#day-10)
- [Set](#set)
@ -35,6 +35,9 @@
- [Getting a value from Map](#getting-a-value-from-map)
- [Checking key in Map](#checking-key-in-map)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises:Level 2](#exerciseslevel-2)
- [Exercises:Level 3](#exerciseslevel-3)
# Day 10
@ -384,39 +387,61 @@ Norway Oslo
## Exercises
### Exercises:Level 1
```js
const a = {4, 5, 8, 9}
const b = {3, 4, 5, 7}
const countries = ['Finland', 'Sweden', 'Norway']
```
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
### Exercises:Level 2
1. Find a union b
2. Find a intersection b
3. Find a with b
### Exercises:Level 3
1. How many languages are there in the countries object file.
1. \*\*\* Use the countries data to 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')]
[
{'English':91},
{'French':45},
{'Arabic':25},
{'Spanish':24},
{'Russian':9},
{'Portuguese':9},
{'Dutch':8},
{'German':7},
{'Chinese':5},
{'Swahili':4},
{'Serbian':4}]
// Your output should look like this
console.log(mostSpokenLanguages(countries, 3))
[
(91, 'English'),
(45, 'French'),
(25, 'Arabic')
]```
````
[
{'English':91},
{'French':45},
{'Arabic':25}
]
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 9](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_higher_order_functions.md) | [Day 11>>](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/11_Day/11_destructuring_and_spreading.md)
[<< Day 9](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) | [Day 11>>](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:10 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:10 Day</h1>
<h2>Set and Map</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')

@ -1,5 +1,5 @@
<div align="center">
<h1> 30 Days Of JavaScript</h1>
<h1> 30 Days Of JavaScript: Destructuring and Spreading</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>
@ -13,9 +13,9 @@
</sub>
</div>
[<< Day 10](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_Set_and_Map.md) | [Day 12>>](#)
[<< Day 10](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | [Day 12>>](../12_Day_Regular_expressions/12_day_regular_expressions.md)
![Day 5](../images/banners/day_1_10.png)
![Day 11](../images/banners/day_1_11.png)
- [Day 11](#day-11)
- [Destructuring and Spread](#destructuring-and-spread)
@ -31,7 +31,10 @@
- [Spread operator to copy array](#spread-operator-to-copy-array)
- [Spread operator to copy object](#spread-operator-to-copy-object)
- [Spread operator with arrow function](#spread-operator-with-arrow-function)
- [Exercise](#exercise)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 11
@ -526,7 +529,9 @@ console.log(sumAllNums(1, 2, 3,4,5))
🌕 You achieved quite a lot so far. Now, your level of JavaScript is upper intermediate. Keep going! You have just completed day 11 challenges and you are 11 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercise
## Exercises
### Exercises: Level 1
```js
const constants = [2.72, 3.14, 9.81, 37, 100]
@ -586,10 +591,108 @@ const users = [
1. Destructure and assign the elements of constants array to e, pi, gravity, humanBodyTemp, waterBoilingTemp.
2. Destructure and assign the elements of countries array to fin, est, sw, den, nor
3. Destructure the rectangle object by its properties or keys.
4. Iterate through the users array and get all the keys of the object using destructuring
5. Find the persons who have less than two skills
6. Destructure the countries object print name, capital, population of all countries
### Exercises: Level 2
1. Iterate through the users array and get all the keys of the object using destructuring
2. Find the persons who have less than two skills
### Exercises: Level 3
1. Destructure the countries object print name, capital, population and languages of all countries
2. A junior developer structure student name, skills and score in array of arrays which may not easy to read. Destructure the following array name to name, skills array to skills, scores array to scores, JavaScript score to jsScore and React score to reactScore variable in one line.
```js
const student = ['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]]
console.log(name, skills, jsScore, reactScore)
```
```sh
David (4) ["HTM", "CSS", "JS", "React"] 90 95
```
3. Write a function called *convertArrayToObject* which can convert the array to a structure object.
```js
const students = [
['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]],
['John', ['HTM', 'CSS', 'JS', 'React'], [85, 80, 85, 80]]
]
console.log(convertArrayToObject(students))
[
{
name: 'David',
skills: ['HTM','CSS','JS','React'],
scores: [98,85,90,95]
},
{
name: 'John',
skills: ['HTM','CSS','JS','React'],
scores: [85, 80,85,80]
}
]
```
4. Copy the student object to newStudent without mutating the original object. In the new object add the following ?
- Add Bootstrap with level 8 to the front end skill sets
- Add Express with level 9 to the back end skill sets
- Add SQL with level 8 to the data base skill sets
- Add SQL without level to the data science skill sets
```js
const student = {
name: 'David',
age: 25,
skills: {
frontEnd: [
{ skill: 'HTML', level: 10 },
{ skill: 'CSS', level: 8 },
{ skill: 'JS', level: 8 },
{ skill: 'React', level: 9 }
],
backEnd: [
{ skill: 'Node',level: 7 },
{ skill: 'GraphQL', level: 8 },
],
dataBase:[
{ skill: 'MongoDB', level: 7.5 },
],
dataScience:['Python', 'R', 'D3.js']
}
}
```
The copied object output should look like this:
```js
{
name: 'David',
age: 25,
skills: {
frontEnd: [
{skill: 'HTML',level: 10},
{skill: 'CSS',level: 8},
{skill: 'JS',level: 8},
{skill: 'React',level: 9},
{skill: 'BootStrap',level: 8}
],
backEnd: [
{skill: 'Node',level: 7},
{skill: 'GraphQL',level: 8},
{skill: 'Express',level: 9}
],
dataBase: [
{ skill: 'MongoDB',level: 7.5},
{ skill: 'SQL',level: 8}
],
dataScience: ['Python','R','D3.js','SQL']
}
}
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 10](https://github.com/Asabeneh/30DaysOfJavaScript/blob/master/09_Day/09_day_Set_and_Map.md) | [Day 12>>](#)
[<< Day 10](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | [Day 12>>](../12_Day_Regular_expressions/12_day_regular_expressions.md)

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:11 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</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,524 @@
<div align="center">
<h1> 30 Days Of JavaScript: Regular Expressions</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 11](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | [Day 13>>](../13_Day_Console_object_methods/13_day_console_object_methods.md)
![Thirty Days Of JavaScript](../images/banners/day_1_12.png)
- [📘 Day 12](#-day-12)
- [Regular Expressions](#regular-expressions)
- [RegExp parameters](#regexp-parameters)
- [Pattern](#pattern)
- [Flags](#flags)
- [Creating a pattern with RegExp Constructor](#creating-a-pattern-with-regexp-constructor)
- [Creating a pattern without RegExp Constructor](#creating-a-pattern-without-regexp-constructor)
- [RegExpp Object Methods](#regexpp-object-methods)
- [Testing for a match](#testing-for-a-match)
- [Array containing all of the match](#array-containing-all-of-the-match)
- [Replacing a substring](#replacing-a-substring)
- [Square Bracket](#square-bracket)
- [Escape character(\\) in RegExp](#escape-character-in-regexp)
- [One or more times(+)](#one-or-more-times)
- [Period(.)](#period)
- [Zero or more times(*)](#zero-or-more-times)
- [Zero or one times(?)](#zero-or-one-times)
- [Quantifier in RegExp](#quantifier-in-regexp)
- [Cart ^](#cart-)
- [Exact match](#exact-match)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📘 Day 12
## Regular Expressions
A regular expression or RegExp is a small programming language that helps to find pattern in data. A RegExp can be used to check if some pattern exists in a different data types. To use RegExp in JavaScript either we use RegExp constructor or we can declare a RegExp pattern using two forward slashes followed by a flag. We can create a pattern in two ways.
To declare a string we use a single quote, double quote a backtick to declare a regular expression we use two forward slashes and an optional flag. The flag could be g, i, m, s, u or y.
### RegExp parameters
A regular expression takes two parameters. One required search pattern and an optional flag.
#### Pattern
A pattern could be a text or any form of pattern which some sort of similarity. For instance the word spam in an email could be a pattern we are interested to look for in an email or a phone number format number might be our interest to look for.
#### Flags
Flags are optional parameters in a regular expression which determine the type of searching. Let see some of the flags:
- g:is a global flag which means looking for a pattern in whole text
- i: case insensitive flag(it searches for both lowercase and uppercase)
- m: multiline
### Creating a pattern with RegExp Constructor
Declaring regular expression without global flag and case insensitive flag.
```js
// without flag
let pattern = 'love'
let regEx = new RegExp(pattern)
```
Declaring regular expression with global flag and case insensitive flag.
```js
let pattern = 'love'
let flag = 'gi'
let regEx = new RegExp(pattern, flag)
```
Declaring a regex pattern using RegExp object. Writing the pattern and the flag inside the RegExp constructor
```js
let regEx = new RegExp('love','gi')
```
### Creating a pattern without RegExp Constructor
Declaring regular expression with global flag and case insensitive flag.
```js
let regEx= /love/gi
```
The above regular expression is the same as the one which we created with RegExp constructor
```js
let regEx= new RegExp('love','gi')
```
### RegExpp Object Methods
Let see some of RegExp methods
#### Testing for a match
*test()*:Tests for a match in a string. It returns true or false.
```js
const str = 'I love JavaScript'
const pattern = /love/
const result = pattern.test(str)
console.log(result)
```
```sh
true
```
#### Array containing all of the match
*match()*:Returns an array containing all of the matches, including capturing groups, or null if no match is found.
If we do not use a global flag, match() returns an array containing the pattern, index, input and group.
```js
const str = 'I love JavaScript'
const pattern = /love/
const result = str.match(pattern)
console.log(result)
```
```sh
["love", index: 2, input: "I love JavaScript", groups: undefined]
```
```js
const str = 'I love JavaScript'
const pattern = /love/g
const result = str.match(pattern)
console.log(result)
```
```sh
["love"]
```
*search()*: Tests for a match in a string. It returns the index of the match, or -1 if the search fails.
```js
const str = 'I love JavaScript'
const pattern = /love/g
const result = str.search(pattern)
console.log(result)
```
```sh
2
```
#### Replacing a substring
*replace()*: Executes a search for a match in a string, and replaces the matched substring with a replacement substring.
```js
const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'
matchReplaced = txt.replace(/Python|python/, 'JavaScript')
console.log(matchReplaced)
```
```sh
JavaScript is the most beautiful language that a human begin has ever created.I recommend python for a first programming language
```
```js
const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'
matchReplaced = txt.replace(/Python|python/g, 'JavaScript')
console.log(matchReplaced)
```
```sh
JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language
```
```js
const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'
matchReplaced = txt.replace(/Python/gi, 'JavaScript')
console.log(matchReplaced)
```
```sh
JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language
```
```js
const txt = '%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing.\
T%he%re i%s n%o%th%ing as m%ore r%ewarding a%s e%duc%at%i%ng a%n%d e%m%p%ow%er%ing \
p%e%o%ple.\
I fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs.\
D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher.'
matches = txt.replace(/%/g, '')
console.log(matches)
```
```sh
I am teacher and I love teaching.There is nothing as more rewarding as educating and empowering people.I found teaching more interesting than any other jobs.Does this motivate you to be a teacher.
```
* []: A set of characters
* [a-c] means, a or b or c
* [a-z] means, any letter a to z
* [A-Z] means, any character A to Z
* [0-3] means, 0 or 1 or 2 or 3
* [0-9] means any number 0 to 9
* [A-Za-z0-9] any character which is a to z, A to Z, 0 to 9
* \\: uses to escape special characters
* \d mean:match where the string contains digits (numbers from 0-9)
* \D mean: match where the string does not contain digits
* . : any character except new line character(\n)
* ^: starts with
* r'^substring' eg r'^love', a sentence which starts with a word love
* r'[^abc] mean not a, not b, not c.
* $: ends with
* r'substring$' eg r'love$', sentence ends with a word love
* *: zero or more times
* r'[a]*' means a optional or it can be occur many times.
* +: one or more times
* r'[a]+' mean at least once or more times
* ?: zero or one times
* r'[a]?' mean zero times or once
* {3}: Exactly 3 characters
* {3,}: At least 3 character
* {3,8}: 3 to 8 characters
* |: Either or
* r'apple|banana' mean either of an apple or a banana
* (): Capture and group
![Regular Expression cheat sheet](../images/regex.png)
Let's use example to clarify the above meta characters
### Square Bracket
Let's use square bracket to include lower and upper case
```js
const pattern = '[Aa]pple' // this square bracket mean either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
const matches = txt.match(pattern)
console.log(matches)
```
```sh
["Apple", index: 0, input: "Apple and banana are fruits. An old cliche says an…by a banana a day keeps the doctor far far away. ", groups: undefined]
```
```js
const pattern = /[Aa]pple/g // this square bracket mean either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
const matches = txt.match(pattern)
console.log(matches)
```
```sh
["Apple", "apple"]
```
If we want to look for the banana, we write the pattern as follows:
```js
const pattern = /[Aa]pple|[Bb]anana/g // this square bracket mean either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. Banana is easy to eat too.'
const matches = txt.match(pattern)
console.log(matches)
```
```sh
["Apple", "banana", "apple", "banana", "Banana"]
```
Using the square bracket and or operator , we manage to extract Apple, apple, Banana and banana.
### Escape character(\\) in RegExp
```js
const pattern = /\d/g // d is a special character which means digits
const txt = 'This regular expression example was made in January 12, 2020.'
const matches = txt. match(pattern)
console.log(matches) // ["1", "2", "2", "0", "2", "0"], this is not what we want
```
```js
const pattern = /\d+/g // d is a special character which means digits
const txt = 'This regular expression example was made in January 12, 2020.'
const matches = txt. match(pattern)
console.log(matches) // ["12", "2020"], this is not what we want
```
### One or more times(+)
```js
const pattern = /\d+/g // d is a special character which means digits
const txt = 'This regular expression example was made in January 12, 2020.'
const matches = txt. match(pattern)
console.log(matches) // ["12", "2020"], this is not what we want
```
### Period(.)
```js
const pattern = /[a]./g // this square bracket means a and . means any character except new line
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)
console.log(matches) // ["an", "an", "an", "a ", "ar"]
```
```js
const pattern = /[a].+/g // . any character, + any character one or more times
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)
console.log(matches) // ['and banana are fruits']
```
### Zero or more times(*)
Zero or many times. The pattern could may not occur or it can occur many times.
```js
const pattern = /[a].*/g //. any character, + any character one or more times
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)
console.log(matches) // ['and banana are fruits']
```
### Zero or one times(?)
Zero or one times. The pattern could may not occur or it may occur once.
```js
const txt = 'I am not sure if there is a convention how to write the word e-mail.\
Some people write it email others may write it as Email or E-mail.'
const pattern = /[Ee]-?mail/g // ? means optional
matches = txt.match(pattern)
console.log(matches) // ["e-mail", "email", "Email", "E-mail"]
```
### Quantifier in RegExp
We can specify the length of the substring we look for in a text, using a curly bracket. Lets imagine, we are interested in substring that their length are 4 characters
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\d{4}/g // exactly four times
const matches = txt.match(pattern)
console.log(matches) // ['2019']
```
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\d{1,4}/g // 1 to 4
const matches = txt.match(pattern)
console.log(matches) // ['6', '2019']
```
### Cart ^
- Starts with
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /^This/ // ^ means starts with
const matches = txt.match(pattern)
console.log(matches) // ['This']
```
- Negation
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /[^A-Za-z,. ]+/g // ^ in set character means negation, not A to Z, not a to z, no space, no coma no period
const matches = txt.match(pattern)
console.log(matches) // ["6", "2019"]
```
### Exact match
It should have ^ starting and $ which is an end.
```js
let pattern = /^[A-Z][a-z]{3,12}$/;
let name = 'Asabeneh';
let result = pattern.test(name)
console.log(result) // true
```
🌕 You are going far. Keep going! Now, you are super charged with the power of regular expression. You have the power to extract and clean any kind of text and you can make meaning out of unstructured data. You have just completed day 12 challenges and you are 12 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises
### Exercises: Level 1
1. Calculate the total annual income of the person from the following text. He earns 4000 euro from salary per month, 10000 euro annual bonus, 5500 euro online courses per month.
1. The position of some particles on the horizontal x-axis -12, -4, -3 and -1 in the negative direction, 0 at origin, 4 and 8 in the positive direction. Extract these numbers and find the distance between the two furthest particles.
```js
points = ['-1', '2', '-4', '-3', '-1', '0', '4', '8']
sortedPoints = [-4, -3, -1, -1, 0, 2, 4, 8]
distance = 12
```
1. Write a pattern which identify if a string is a valid JavaScript variable
```sh
is_valid_variable('first_name') # True
is_valid_variable('first-name') # False
is_valid_variable('1first_name') # False
is_valid_variable('firstname') # True
```
### Exercises: Level 2
1. Write a function called *tenMostFrequentWords* which get the ten most frequent word from a string?
```js
paragraph = `I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.`
console.log(tenMostFrequentWords(paragraph))
```
```sh
[
{word:'love', count:6},
{word:'you', count:5},
{word:'can', count:3},
{word:'what', count:2},
{word:'teaching', count:2},
{word:'not', count:2},
{word:'else', count:2},
{word:'do', count:2},
{word:'I', count:2},
{word:'which', count:1},
{word:'to', count:1},
{word:'the', count:1},
{word:'something', count:1},
{word:'if', count:1},
{word:'give', count:1},
{word:'develop',count:1},
{word:'capabilities',count:1},
{word:'application', count:1},
{word:'an',count:1},
{word:'all',count:1},
{word:'Python',count:1},
{word:'If',count:1}]
```
```js
console.log(tenMostFrequentWords(paragraph, 10))
```
```sh
[{word:'love', count:6},
{word:'you', count:5},
{word:'can', count:3},
{word:'what', count:2},
{word:'teaching', count:2},
{word:'not', count:2},
{word:'else', count:2},
{word:'do', count:2},
{word:'I', count:2},
{word:'which', count:1}
]
```
### Exercises: Level 3
1. Writ a function which cleans text. Clean the following text. After cleaning, count three most frequent words in the string.
```js
sentence = `%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?`
console.log(cleanText(sentence))
```
```sh
I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher
```
1. Write a function which find the most frequent words. After cleaning, count three most frequent words in the string.
```js
console.log(mostFrequentWords(cleanedText))
[{word:'I', count:3}, {word:'teaching', count:2}, {word:'teacher', count:2}]
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 11](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | [Day 13>>](../13_Day_Console_object_methods/13_day_console_object_methods.md)

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:11 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</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,358 @@
<div align="center">
<h1> 30 Days Of JavaScript: Console Object Methods</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 12](../12_Day_Regular_expressions/12_day_regular_expressions.md) | [Day 14>>](../14_Day_Error_handling/14_day_error_handling.md)
![Thirty Days Of JavaScript](../images/banners/day_1_13.png)
- [Day 13](#day-13)
- [Console Object Methods](#console-object-methods)
- [console.log()](#consolelog)
- [console.warn()](#consolewarn)
- [console.error()](#consoleerror)
- [console.table()](#consoletable)
- [console.time()](#consoletime)
- [console.info()](#consoleinfo)
- [console.assert()](#consoleassert)
- [console.group()](#consolegroup)
- [console.count()](#consolecount)
- [console.clear()](#consoleclear)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises:Level 2](#exerciseslevel-2)
- [Exercises:Level 3](#exerciseslevel-3)
# Day 13
## Console Object Methods
In this section, we will cover about console and console object methods. Absolute beginners usually do not know which to use: console.log(), document.write() or document.getElementById.
We use console object methods to show output on the browser console and we use document.write to show output on the browser document(view port). Both methods used only for testing and debugging purposes. The console method is the most popular testing and debugging tool on the browser. We use document.getElementById() when we like to interact with DOM try using JavaScript. We will cover DOM in another section.
In addition to the famous, console.log() method, the console provides other more methods methods.
### console.log()
We use console.log() to show output on the browser console. We can substitute values and also we can style the logging out put using %c.
- Showing output on browser console
```js
console.log('30 Days of JavaScript')
```
```sh
30 Days of JavaScript
```
- Substitution
```js
console.log('%d %s of JavaScript', 30, 'Days')
```
```sh
30 Days of JavaScript
```
- CSS
We can style logging message using css. Copy the following code and paste it on browser console to see the result.
```js
console.log('%c30 Days Of JavaScript', 'color:green') // log output is green
console.log(
'%c30 Days%c %cOf%c %cJavaScript%c',
'color:green',
'',
'color:red',
'',
'color:yellow'
) // log output green red and yellow text
```
### console.warn()
We use console.warn() to give warning on browser. For instance to inform or warn deprecation of version of a package or bad practices. Copy the following code and paste it on browser console to see warning messages.
```js
console.warn('This is a warning')
console.warn(
'You are using React. Do not touch the DOM. Virtual DOM will take care of handling the DOM!'
)
console.warn('Warning is different from error')
```
### console.error()
The console.error() methods shows an error messages.
```js
console.error('This is an error message')
console.error('We all make mistakes')
```
### console.table()
The console.table() method display data as a table on the console. Displays tabular data as a table. The console.table() takes one required argument data, which must be an array or an object, and one additional optional parameter columns.
Let us first start with a simple array. The code below displays a table with two columns. An index column to display the index and value column to display the names
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
console.table(names)
```
Let us also check the result of an object. This creates table with two columns:an index column containing the keys and a value column contain the values of the object.
```js
const user = {
name: 'Asabeneh',
title: 'Programmer',
country: 'Finland',
city: 'Helsinki',
age: 250
}
console.table(user)
```
Check the rest of the examples by copying and paste on the browser console.
```js
const countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo']
]
console.table(countries)
```
```js
const users = [
{
name: 'Asabeneh',
title: 'Programmer',
country: 'Finland',
city: 'Helsinki',
age: 250
},
{
name: 'Eyob',
title: 'Teacher',
country: 'Sweden',
city: 'London',
age: 25
},
{
name: 'Asab',
title: 'Instructor',
country: 'Norway',
city: 'Oslo',
age: 22
},
{
name: 'Matias',
title: 'Developer',
country: 'Denmark',
city: 'Copenhagen',
age: 28
}
]
console.table(users)
```
### console.time()
Starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.
```js
const countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo']
]
console.time('Regular for loop')
for (let i = 0; i < countries.length; i++) {
console.log(countries[i][0], countries[i][1])
}
console.timeEnd('Regular for loop')
console.time('for of loop')
for (const [name, city] of countries) {
console.log(name, city)
}
console.timeEnd('for of loop')
console.time('forEach loop')
countries.forEach(([name, city]) => {
console.log(name, city)
})
console.timeEnd('forEach loop')
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
Regular for loop: 0.34716796875ms
Finland Helsinki
Sweden Stockholm
Norway Oslo
for of loop: 0.26806640625ms
Finland Helsinki
Sweden Stockholm
Norway Oslo
forEach loop: 0.358154296875ms
```
According the above output the regular for loop is slower than for of or forEach loop.
### console.info()
It display information message on browser console.
```js
console.info('30 Days Of JavaScript challenge is trending on Github')
console.info('30 Days Of fullStack challenge might be released')
console.info('30 Days Of HTML and CSS challenge might be released')
```
### console.assert()
The console.assert() methods writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. The first parameter is an assertion expression. If this expression is false, an Assertion failed error message will be displayed.
```js
console.assert(4 > 3, '4 is greater than 3') // no result
console.assert(3 > 4, '3 is not greater than 4') // Assertion failed: 3 is not greater than 4
for (let i = 0; i <= 10; i += 1) {
let errorMessage = `${i} is not even`
console.log('the # is ' + i)
console.assert(i % 2 === 0, { number: i, errorMessage: errorMessage })
}
```
### console.group()
The console.group() can help to group different log groups. Copy the following code and paste it on browser console to the groups.
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
const countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo']
]
const user = {
name: 'Asabeneh',
title: 'Programmer',
country: 'Finland',
city: 'Helsinki',
age: 250
}
const users = [
{
name: 'Asabeneh',
title: 'Programmer',
country: 'Finland',
city: 'Helsinki',
age: 250
},
{
name: 'Eyob',
title: 'Teacher',
country: 'Sweden',
city: 'London',
age: 25
},
{
name: 'Asab',
title: 'Instructor',
country: 'Norway',
city: 'Oslo',
age: 22
},
{
name: 'Matias',
title: 'Developer',
country: 'Denmark',
city: 'Copenhagen',
age: 28
}
]
console.group('Names')
console.log(names)
console.groupEnd()
console.group('Countries')
console.log(countries)
console.groupEnd()
console.group('Users')
console.log(user)
console.log(users)
console.groupEnd()
```
### console.count()
It prints the number of time this console.count() is called. It takes a string label parameter. It is very helpful to count the number of times a function is called. In the following example, the console.count() method will run three times
```js
const func = () => {
console.count('Function has been called')
}
func()
func()
func()
```
```sh
Function has been called: 1
Function has been called: 2
Function has been called: 3
```
### console.clear()
The console.clear() cleans the browser console.
🌕 Keep up the good work. Keep pushing, the sky is the limit! You have just completed day 13 challenges and you are 13 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
### Exercises:Level 1
1. Display the countries array as a table
2. Display the countries object as a table
3. Use console.group() to group logs
### Exercises:Level 2
1. 10 > 2 \* 10 use console.assert()
2. Write a warning message using console.warn()
3. Write an error message using console.error()
### Exercises:Level 3
1. Check the speed difference among the following loops: while, for, for of, forEach
🎉 CONGRATULATIONS ! 🎉
[<< Day 12](../12_Day_Regular_expressions/12_day_regular_expressions.md) | [Day 14>>](../14_Day_Error_handling/14_day_error_handling.md)

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:13 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:13 Day</h1>
<h2>Console Object Methods</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,193 @@
<div align="center">
<h1> 30 Days Of JavaScript: Error handling</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 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md)
![Thirty Days Of JavaScript](../images/banners/day_1_14.png)
- [Day 14](#day-14)
- [Error Handling](#error-handling)
- [Error Types](#error-types)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises:Level](#exerciseslevel)
# Day 14
## Error Handling
JavaScript is a loosely-typed language. Some times you will get a runtime error when you try to access an undefined variable or call undefined function etc.
JavaScript similar to python or Java provides an error-handling mechanism to catch runtime errors using try-catch-finally block.
```js
try {
// code that may throw an error
} catch (err) {
// code to be executed if an error occurs
} finally {
// code to be executed regardless of an error occurs or not
}
```
**try**: wrap suspicious code that may throw an error in try block.The try statement allows us to define a block of code to be tested for errors while it is being executed.
**catch**: write code to do something in catch block when an error occurs. The catch block can have parameters that will give you error information. Catch block is used to log an error or display specific messages to the user.
**finally**: finally block will always be executed regardless of the occurrence of an error. The finally block can be used to complete the remaining task or reset variables that might have changed before error occurred in try block.
**Example:**
```js
try {
let lastName = 'Yetayeh'
let fullName = fistName + ' ' + lastName
} catch (err) {
console.log(err)
}
```
```sh
ReferenceError: fistName is not defined
at <anonymous>:4:20
```
```js
try {
let lastName = 'Yetayeh'
let fullName = fistName + ' ' + lastName
} catch (err) {
console.error(err) // we can use console.log() or console.error()
} finally {
console.log('In any case I will be executed')
}
```
```sh
ReferenceError: fistName is not defined
at <anonymous>:4:20
In any case I will be executed
```
The catch block take a parameter. It is common to pass e, err or error as a parameter to the catch block. This parameter is an object and it has name and message keys. Lets use the name and message.
```js
try {
let lastName = 'Yetayeh'
let fullName = fistName + ' ' + lastName
} catch (err) {
console.log('Name of the error', err.name)
console.log('Error message', err.message)
} finally {
console.log('In any case I will be executed')
}
```
```sh
Name of the error ReferenceError
Error message fistName is not defined
In any case I will be executed
```
throw: the throw statement allows us to create a custom error. We can through a string, number, boolean or an object. Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:
```js
throw 'Error2' // generates an exception with a string value
throw 42 // generates an exception with the value 42
throw true // generates an exception with the value true
throw new Error('Required') // generates an error object with the message of Required
```
```js
const throwErroExampleFun = () => {
let message
let x = prompt('Enter a number: ')
try {
if (x == '') throw 'empty'
if (isNaN(x)) throw 'not a number'
x = Number(x)
if (x < 5) throw 'too low'
if (x > 10) throw 'too high'
} catch (err) {
console.log(err)
}
}
throwErroExampleFun()
```
### Error Types
- ReferenceError: An illegal reference has occurred. A ReferenceError is thrown if we use a variable that has not been declared.
```js
let firstName = 'Asabeneh'
let fullName = firstName + ' ' + lastName
console.log(fullName)
```
```sh
Uncaught ReferenceError: lastName is not defined
at <anonymous>:2:35
```
- SyntaxError: A syntax error has occurred
```js
let square = 2 x 2
console.log(square)
console.log('Hello, world")
```
```sh
Uncaught SyntaxError: Unexpected identifier
```
- TypeError: A type error has occurred
```js
let num = 10
console.log(num.toLowerCase())
```
```sh
Uncaught TypeError: num.toLowerCase is not a function
at <anonymous>:2:17
```
These are some of the common error you may face when you write a code. Understanding errors can help you to know what mistakes you made and it will help you to debug your code fast.
🌕 You are flawless. Now, you knew how to handle errors and you can write robust application which handle unexpected user inputs. You have just completed day 14 challenges and you are 14 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
### Exercises:Level 1
Practice
### Exercises: Level 2
Practice
### Exercises:Level
Practice
🎉 CONGRATULATIONS ! 🎉
[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:12 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:14 Day</h1>
<h2>DOM</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,715 @@
<div align="center">
<h1> 30 Days Of JavaScript: Classes</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 14](../14_Day_Error_handling/14_day_error_handling.md) | [Day 16>>](../16_Day_JSON/16_day_json.md)
![Thirty Days Of JavaScript](../images/banners/day_1_15.png)
- [Day 15](#day-15)
- [Classes](#classes)
- [Defining a classes](#defining-a-classes)
- [Class Instantiation](#class-instantiation)
- [Class Constructor](#class-constructor)
- [Default values with constructor](#default-values-with-constructor)
- [Class methods](#class-methods)
- [Properties with initial value](#properties-with-initial-value)
- [getter](#getter)
- [setter](#setter)
- [Static method](#static-method)
- [Inheritance](#inheritance)
- [Overriding methods](#overriding-methods)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Exercises Level 3](#exercises-level-3)
# Day 15
## Classes
JavaScript is an object oriented programming language. Everything in JavScript is an object, with its properties and methods. We create class to create an object. A Class is like an object constructor, or a "blueprint" for creating objects. We instantiate a class to create an object. The class defines attributes and the behavior of the object, while the object, on the other hand, represents the class.
Once we create a class we can create object from it whenever we want. Creating an object from a class is called class instantiation.
In the object section, we saw how to create an object literal. Object literal is a singleton. If we want to get a similar object , we have to write it. However, class allows to create many objects. This helps to reduce amount of code and repetition of code.
### Defining a classes
To define a class in JavaScript we need the keyword _class_ , the name of a class in **CamelCase** and block code(two curly brackets). Let us create a class name Person.
```sh
// syntax
class ClassName {
// code goes here
}
```
**Example:**
```js
class Person {
// code goes here
}
```
We have created an Person class but it does not have any thing inside.
### Class Instantiation
Instantiation class means creating an object from a class. We need the keyword _new_ and we call the name of the class after the word new.
Let us create a dog object from our Person class.
```js
class Person {
// code goes here
}
const person = new Person()
console.log(person)
```
```sh
Person {}
```
As you can see, we have created a person object. Since the class did not have any properties yet the object is also empty.
Let use the class constructor to pass different properties for the class.
### Class Constructor
The constructor is a builtin function which allows as to create a blueprint for our object. The constructor function starts with a keyword constructor followed by a parenthesis. Inside the parenthesis we pass the properties of the object as parameter. We use the _this_ keyword to attach the constructor parameters with the class.
The following Person class constructor has firstName and lastName property. These properties are attached to the Person class using _this_ keyword. _This_ refers to the class itself.
```js
class Person {
constructor(firstName, lastName) {
console.log(this) // Check the output from here
this.firstName = firstName
this.lastName = lastName
}
}
const person = new Person()
console.log(person)
```
```sh
Person {firstName: undefined, lastName}
```
All the keys of the object are undefined. When ever we instantiate we should pass the value of the properties. Let us pass value at this time when we instantiate the class.
```js
class Person {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}
const person1 = new Person('Asabeneh', 'Yetayeh')
console.log(person1)
```
```sh
Person {firstName: "Asabeneh", lastName: "Yetayeh"}
```
As we have stated at the very beginning that once we create a class we can create many object using the class. Now, let us create many person objects using the Person class.
```js
class Person {
constructor(firstName, lastName) {
console.log(this) // Check the output from here
this.firstName = firstName
this.lastName = lastName
}
}
const person1 = new Person('Asabeneh', 'Yetayeh')
const person2 = new Person('Lidiya', 'Tekle')
const person3 = new Person('Abraham', 'Yetayeh')
console.log(person1)
console.log(person2)
console.log(person3)
```
```sh
Person {firstName: "Asabeneh", lastName: "Yetayeh"}
Person {firstName: "Lidiya", lastName: "Tekle"}
Person {firstName: "Abraham", lastName: "Yetayeh"}
```
Using the class Person we created three persons object. As you can see our class did not many properties let us add more properties to the class.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
console.log(this) // Check the output from here
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
console.log(person1)
```
```sh
Person {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki"}
```
### Default values with constructor
The constructor function properties may have a default value like other regular functions.
```js
class Person {
constructor(
firstName = 'Asabeneh',
lastName = 'Yetayeh',
age = 250,
country = 'Finland',
city = 'Helsinki'
) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
}
}
const person1 = new Person() // it will take the default values
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
console.log(person1)
console.log(person2)
```
```sh
Person {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki"}
Person {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Espoo"}
```
### Class methods
The constructor inside a class is a builtin function which allow us to create a blueprint for the object. In a class we can create class methods. Methods are JavaScript functions inside the class. Let us create some class methods.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
console.log(person1.getFullName())
console.log(person2.getFullName())
```
```sh
Asabeneh Yetayeh
test.js:19 Lidiya Tekle
```
### Properties with initial value
When we create a class for some properties we may have an initial value. For instance if you are playing a game, you starting score will be zero. So, we may have a starting score or score which is zero. In other way, we may have an initial skill and we will acquire some skill after some time.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
console.log(person1.score)
console.log(person2.score)
console.log(person1.skills)
console.log(person2.skills)
```
```sh
0
0
[]
[]
```
A method could be regular method or a getter or a setter. Let us see, getter and setter.
### getter
The get method allow us to access value from the object. We write a get method using keyword _get_ followed by a function. Instead of accessing properties directly from the object we use getter to get the value. See the example bellow
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getscore() {
return this.score
}
get getSkills() {
return this.skills
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
console.log(person1.getScore) // We do not need parenthesis to call a getter method
console.log(person2.getScore)
console.log(person1.getSkills)
console.log(person2.getSkills)
```
```sh
0
0
[]
[]
```
### setter
The setter method allow us to modify the value of certain properties. We write a setter method using keyword _set_ followed by a function. See the example bellow.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getScore() {
return this.score
}
get getSkills() {
return this.skills
}
set setScore(score) {
this.score += score
}
set setSkill(skill) {
this.skills.push(skill)
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
person1.setScore = 1
person1.setSkill = 'HTML'
person1.setSkill = 'CSS'
person1.setSkill = 'JavaScript'
person2.setScore = 1
person2.setSkill = 'Planning'
person2.setSkill = 'Managing'
person2.setSkill = 'Organizing'
console.log(person1.score)
console.log(person2.score)
console.log(person1.skills)
console.log(person2.skills)
```
```sh
1
1
["HTML", "CSS", "JavaScript"]
["Planning", "Managing", "Organizing"]
```
Do not be puzzled by the difference between regular method and a getter. If you know how to make a regular method you are good. Let us add regular method called getPersonInfo in the Person class.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getScore() {
return this.score
}
get getSkills() {
return this.skills
}
set setScore(score) {
this.score += score
}
set setSkill(skill) {
this.skills.push(skill)
}
getPersonInfo() {
let fullName = this.getFullName()
let skills =
this.skills.length > 0 &&
this.skills.slice(0, this.skills.length - 1).join(', ') +
` and ${this.skills[this.skills.length - 1]}`
let formattedSkills = skills ? `He knows ${skills}` : ''
let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`
return info
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
const person3 = new Person('John', 'Doe', 50, 'Mars', 'Mars city')
person1.setScore = 1
person1.setSkill = 'HTML'
person1.setSkill = 'CSS'
person1.setSkill = 'JavaScript'
person2.setScore = 1
person2.setSkill = 'Planning'
person2.setSkill = 'Managing'
person2.setSkill = 'Organizing'
console.log(person1.getScore)
console.log(person2.getScore)
console.log(person1.getSkills)
console.log(person2.getSkills)
console.log(person3.getSkills)
console.log(person1.getPersonInfo())
console.log(person2.getPersonInfo())
console.log(person3.getPersonInfo())
```
```sh
1
1
["HTML", "CSS", "JavaScript"]
["Planning", "Managing", "Organizing"]
[]
Asabeneh Yetayeh is 250. He lives Helsinki, Finland. He knows HTML, CSS and JavaScript
Lidiya Tekle is 28. He lives Espoo, Finland. He knows Planning, Managing and Organizing
John Doe is 50. He lives Mars city, Mars.
```
### Static method
The static keyword defines a static method for a class. Static methods are not called on instances of the class. Instead, they are called on the class itself. These are often utility functions, such as functions to create or clone objects. An example of static method is _Date.now()_. The _now_ method is called directly from the class.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getScore() {
return this.score
}
get getSkills() {
return this.skills
}
set setScore(score) {
this.score += score
}
set setSkill(skill) {
this.skills.push(skill)
}
getPersonInfo() {
let fullName = this.getFullName()
let skills =
this.skills.length > 0 &&
this.skills.slice(0, this.skills.length - 1).join(', ') +
` and ${this.skills[this.skills.length - 1]}`
let formattedSkills = skills ? `He knows ${skills}` : ''
let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`
return info
}
static favoriteSkill() {
const skills = ['HTML', 'CSS', 'JS', 'React', 'Python', 'Node']
const index = Math.floor(Math.random() * skills.length)
return skills[index]
}
static showDateTime() {
let now = new Date()
let year = now.getFullYear()
let month = now.getMonth() + 1
let date = now.getDate()
let hours = now.getHours()
let minutes = now.getMinutes()
if (hours < 10) {
hours = '0' + hours
}
if (minutes < 10) {
minutes = '0' + minutes
}
let dateMonthYear = date + '.' + month + '.' + year
let time = hours + ':' + minutes
let fullTime = dateMonthYear + ' ' + time
return fullTime
}
}
console.log(Person.favoriteSkill())
console.log(Person.showDateTime())
```
```sh
Node
15.1.2020 23:56
```
The static methods are methods which can be used as utility functions.
## Inheritance
Using inheritance we can access all the properties and the methods of the parent class. This reduces repetition of code. If you remember, we have a Person parent class and we will create children from it. Our children class could be student, teach etc.
```js
// syntax
class ChildClassName extends {
// code goes here
}
```
Let us create a Student child class from Person parent class.
```js
class Student extends Person {
saySomething() {
console.log('I am a child of the person class')
}
}
const s1 = new Student('Asabeneh', 'Yetayeh', 'Finland', 250, 'Helsinki')
console.log(s1)
console.log(s1.saySomething())
console.log(s1.getFullName())
console.log(s1.getPersonInfo())
```
```sh
Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …}
I am a child of the person class
Asabeneh Yetayeh
Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …}
Asabeneh Yetayeh is Finland. He lives Helsinki, 250.
```
### Overriding methods
As you can see, we manage to access all the methods in the Person Class and we used it in the Student child class. We can customize the parent methods, we can add additional properties to a child class. If we want to customize, the methods and if we want to add extra properties, we need to use the constructor function the child class too. In side the constructor function we call the super() function to access all the properties from the parent class. The Person class didn't have gender but now let us give gender property for the child class, Student. If the same method name used in the child class, the parent method will be overridden.
```js
class Student extends Person {
constructor(firstName, lastName, age, country, city, gender) {
super(firstName, lastName, age, country, city)
this.gender = gender
}
saySomething() {
console.log('I am a child of the person class')
}
getPersonInfo() {
let fullName = this.getFullName()
let skills =
this.skills.length > 0 &&
this.skills.slice(0, this.skills.length - 1).join(', ') +
` and ${this.skills[this.skills.length - 1]}`
let formattedSkills = skills ? `He knows ${skills}` : ''
let pronoun = this.gender == 'Male' ? 'He' : 'She'
let info = `${fullName} is ${this.age}. ${pronoun} lives in ${this.city}, ${this.country}. ${formattedSkills}`
return info
}
}
const s1 = new Student(
'Asabeneh',
'Yetayeh',
250,
'Finland',
'Helsinki',
'Male'
)
const s2 = new Student('Lidiya', 'Tekle', 28, 'Finland', 'Helsinki', 'Female')
s1.setScore = 1
s1.setSkill = 'HTML'
s1.setSkill = 'CSS'
s1.setSkill = 'JavaScript'
s2.setScore = 1
s2.setSkill = 'Planning'
s2.setSkill = 'Managing'
s2.setSkill = 'Organizing'
console.log(s1)
console.log(s1.saySomething())
console.log(s1.getFullName())
console.log(s1.getPersonInfo())
console.log(s2.saySomething())
console.log(s2.getFullName())
console.log(s2.getPersonInfo())
```
```sh
Student {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki", …}
Student {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Helsinki", …}
I am a child of the person class
Asabeneh Yetayeh
Student {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki", …}
Asabeneh Yetayeh is 250. He lives in Helsinki, Finland. He knows HTML, CSS and JavaScript
I am a child of the person class
Lidiya Tekle
Student {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Helsinki", …}
Lidiya Tekle is 28. She lives in Helsinki, Finland. He knows Planning, Managing and Organizing
```
Now, the getPersonInfo method has been overridden and it identifies if the person is male or female.
🌕 You are excelling. Now, you knew class and you have the power to turn everything to an object. You made it to half way to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
### Exercises Level 1
1. Create an Animal class. The class will have name, age, color, legs properties and create different methods
2. Create a Dog and Cat child class from the Animal Class.
### Exercises Level 2
1. Override the method you create in Animal class
### Exercises Level 3
1. Let's 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 a class called Statistics and create all the functions which do statistical calculations as method for the Statistics class. Check the output below.
```JS
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
// you output should look like this
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)]
```
1. Create a class 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 also a set of expenses and its description.
🎉 CONGRATULATIONS ! 🎉
[<< Day 14](../14_Day_Error_handling/14_day_error_handling.md) | [Day 16>>](../16_Day_JSON/16_day_json.md)

File diff suppressed because it is too large Load Diff

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

@ -0,0 +1,105 @@
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getScore() {
return this.score
}
get getSkills() {
return this.skills
}
set setScore(score) {
this.score += score
}
set setSkill(skill) {
this.skills.push(skill)
}
getPersonInfo() {
let fullName = this.getFullName()
let skills =
this.skills.length > 0 &&
this.skills.slice(0, this.skills.length - 1).join(', ') +
` and ${this.skills[this.skills.length - 1]}`
let formattedSkills = skills ? `He knows ${skills}` : ''
let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`
console.log(this)
return info
}
static favoriteSkill() {
const skills = ['HTML', 'CSS', 'JS', 'React', 'Python', 'Node']
const index = Math.floor(Math.random() * skills.length)
console.log('hi')
return skills[index]
}
}
console.log(Person.favoriteSkill())
class Student extends Person {
constructor(firstName, lastName, age, country, city, gender) {
super(firstName, lastName, age, country, city)
this.gender = gender
}
saySomething() {
console.log('I am a child of the person class')
}
getPersonInfo() {
let fullName = this.getFullName()
let skills =
this.skills.length > 0 &&
this.skills.slice(0, this.skills.length - 1).join(', ') +
` and ${this.skills[this.skills.length - 1]}`
let formattedSkills = skills ? `He knows ${skills}` : ''
let pronoun = this.gender == 'Male' ? 'He' : 'She'
let info = `${fullName} is ${this.age}. ${pronoun} lives in ${this.city}, ${this.country}. ${formattedSkills}`
console.log(this)
return info
}
}
const s1 = new Student(
'Asabeneh',
'Yetayeh',
250,
'Finland',
'Helsinki',
'Male'
)
const s2 = new Student('Lidiya', 'Tekle', 28, 'Finland', 'Helsinki', 'Female')
s1.setScore = 1
s1.setSkill = 'HTML'
s1.setSkill = 'CSS'
s1.setSkill = 'JavaScript'
s2.setScore = 1
s2.setSkill = 'Planning'
s2.setSkill = 'Managing'
s2.setSkill = 'Organizing'
console.log(s1)
console.log(s2)
console.log(s1.saySomething())
console.log(s1.getFullName())
console.log(s1.getPersonInfo())
console.log(s2.saySomething())
console.log(s2.getFullName())
console.log(s2.getPersonInfo())

@ -0,0 +1,597 @@
<div align="center">
<h1> 30 Days Of JavaScript: JSON</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 15](../15_Day_Classes/15_day_classes.md) | [Day 17 >>](../17_Day_Web_storages/17_day_web_storages.md)
![Thirty Days Of JavaScript](../images/banners/day_1_16.png)
- [Day 16](#day-16)
- [JSON](#json)
- [Converting JSON to JavaScript Object](#converting-json-to-javascript-object)
- [JSON.parse()](#jsonparse)
- [Using a reviver function with JSON.parse()](#using-a-reviver-function-with-jsonparse)
- [Converting Object to JSON](#converting-object-to-json)
- [Using a Filter Array with JSON.stringify](#using-a-filter-array-with-jsonstringify)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Exercises Level 3](#exercises-level-3)
# Day 16
## JSON
JSON stands for JavaScript Object Notation. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text or string only. JSON is a light weight data format for storing and transporting. JSON is mostly used when data is sent from a server to a client. JSON is an easier-to-use alternative to XML.
**Example:**
```js
{
"users":[
{
"firstName":"Asabeneh",
"lastName":"Yetayeh",
"age":250,
"email":"asab@asb.com"
},
{
"firstName":"Alex",
"lastName":"James",
"age":25,
"email":"alex@alex.com"
},
{
"firstName":"Lidiya",
"lastName":"Tekle",
"age":28,
"email":"lidiya@lidiya.com"
}
]
}
```
The above JSON example is not much different for a normal object. Then, what is the difference ? The difference is the key of a JSON object should be with double quotes or it should be a string. JavaScript Object and JSON are very similar that we can change JSON to Object and Object to JSON.
Let us see the above example in more detail, it starts with a curly bracket. Inside the curly bracket, there is "users" key which has a value array. Inside the array we have different objects and each objects has keys, each keys has to have double quotes. For instance, we use "firstNaMe" instead of just firstName, however in object we use keys without double quotes. This is the major difference between an object and a JSON. Let's see more examples about JSON.
**Example:**
```js
{
"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
}
}
```
### Converting JSON to JavaScript Object
Mostly we fetch JSON data from HTTP response or from a file, but we can store the JSON as a string and we can change to Object for sake of demonstration. In JavaScript the keyword _JSON_ has _parse()_ and _stringify()_ methods. When we want to change the JSON to an object we parse the JSON using _JSON.parse()_. When we want to change the object to JSON we use _JSON.stringify()_.
#### JSON.parse()
```js
JSON.parse(json[, reviver])
// json or text , the data
// reviver is an optional callback function
```
```js
const usersText = `{
"users":[
{
"firstName":"Asabeneh",
"lastName":"Yetayeh",
"age":250,
"email":"asab@asb.com"
},
{
"firstName":"Alex",
"lastName":"James",
"age":25,
"email":"alex@alex.com"
},
{
"firstName":"Lidiya",
"lastName":"Tekle",
"age":28,
"email":"lidiya@lidiya.com"
}
]
}`
const usersObj = JSON.parse(usersText, undefined, 4)
console.log(usersObj)
```
### Using a reviver function with JSON.parse()
To use the reviver function as a formatter, we put the keys we want to format first name and last name value. Let us say, we are interested to format the firstName and lastName of the JSON data .
```js
const usersText = `{
"users":[
{
"firstName":"Asabeneh",
"lastName":"Yetayeh",
"age":250,
"email":"asab@asb.com"
},
{
"firstName":"Alex",
"lastName":"James",
"age":25,
"email":"alex@alex.com"
},
{
"firstName":"Lidiya",
"lastName":"Tekle",
"age":28,
"email":"lidiya@lidiya.com"
}
]
}`
const usersObj = JSON.parse(usersText, (key, value) => {
let newValue =
typeof value == 'string' && key != 'email' ? value.toUpperCase() : value
return newValue
})
console.log(usersObj)
```
The _JSON.parse()_ is very handy to use. You do not have to pass optional parameter, you can just use it with the required parameter and you will achieve quite a lot.
### Converting Object to JSON
When we want to change the object to JSON we use _JSON.stringify()_. The stringify method takes one required parameter and two optional parameters. The replacer is used as filter and the space is an indentations. If we do not want to filter out any of the keys from the object we can just pass undefined.
```js
JSON.stringify(obj, replacer, space)
// json or text , the data
// reviver is an optional callback function
```
Let us convert the following object to a string. First let use keep all the keys and also let us have 4 space indentation.
```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
}
}
const txt = JSON.stringify(users, undefined, 4)
console.log(txt) // text means JSON- because json is a string form of an object.
```
```sh
{
"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
}
}
```
### Using a Filter Array with JSON.stringify
Now, lets use the replacer as a filter. The user object has long list of keys but we are interested only in few of them. We put the keys we want to keep in array as show in the example and use it the place of the replacer.
```js
const user = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
country: 'Finland',
city: 'Helsinki',
email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Pyhton'],
age: 250,
isLoggedIn: false,
points: 30
}
const txt = JSON.stringify(user,['firstName', 'lastName', 'country', 'city', 'age'],4)
console.log(txt)
```
```sh
{
"firstName": "Asabeneh",
"lastName": "Yetayeh",
"country": "Finland",
"city": "Helsinki",
"age": 250
}
```
🌕 You are extraordinary. Now, you knew a light-weight data format which you may use to store data or to send it an HTTP server. You are 16 steps a head to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
```js
const skills = ['HTML', 'CSS', 'JS', 'React','Node', 'Python']
let age = 250;
let isMarried = true
const student = {
firstName:'Asabeneh',
lastName:'Yetayehe',
age:250,
isMarried:true,
skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ]
}
const txt = `{
"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
}
}
`
```
### Exercises Level 1
1. Change skills array to JSON using JSON.stringify()
1. Stringify the age variable
1. Stringify the isMarried variable
1. Stringify the student object
### Exercises Level 2
1. Stringify the students object with only firstName, lastName and skills properties
### Exercises Level 3
1. Parse the *txt* JSON to object.
2. Find the the user who has many skills from the variable stored in *txt*.
🎉 CONGRATULATIONS ! 🎉
[<< Day 15](../15_Day_Classes/15_day_classes.md) | [Day 17 >>](../17_Day_Web_storages/17_day_web_storages.md)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:16 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:16 Day</h1>
<h2>JSON</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')

File diff suppressed because it is too large Load Diff

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

@ -0,0 +1,233 @@
<div align="center">
<h1> 30 Days Of JavaScript: Web Storages</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 16](../16_Day_JSON/16_day_json.md) | [Day 18 >>](../18_Day_Promises/18_day_promises.md)
![Thirty Days Of JavaScript](../images/banners/day_1_17.png)
- [Day 17](#day-17)
- [HTML5 Web Storage](#html5-web-storage)
- [sessionStorage](#sessionstorage)
- [localStorage](#localstorage)
- [Use case of Web Storages](#use-case-of-web-storages)
- [HTML5 Web Storage Objects](#html5-web-storage-objects)
- [Setting item to the localStorage](#setting-item-to-the-localstorage)
- [Getting item from localStorage](#getting-item-from-localstorage)
- [Clearing the localStorage](#clearing-the-localstorage)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 17
## HTML5 Web Storage
Web Storage(sessionStorage and localStorage) is a new HTML5 API offering important benefits over traditional cookies. Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. The data storage limit of cookies in many web browsers is about 4 KB per cookie. We Storages can store far larger data (at least 5MB) and never transferred to the server. All sites from the same or one origin can store and access the same data.
The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases. The are are two Web Storage objects:
- sessionStorage
- localStorage
localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.
It should be noted that data stored in either localStorage or sessionStorage is specific to the protocol of the page.
The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
![web_storage](../images/web_storage.png)
### sessionStorage
sessionStorage is only available within the browser tab or window session. Its designed to store data in a single web page session. That means if the window is closed the session data will be removed. Since sessionStorage and localStorage has similar methods, we will focus only on localStorage.
### localStorage
The HTML5 localStorage is the para of the web storage API which is used to store data on the browser with no expiration data. The data will be available on the browser even after the browser is closed. localStorage is kept even between browser sessions. This means data is still available when the browser is closed and reopened, and also instantly between tabs and windows.
Web Storage data is, in both cases, not available between different browsers. For example, storage objects created in Firefox cannot be accessed in Internet Explorer, exactly like cookies. There are five methods to work on local storage:
_setItem(), getItem(), removeItem(), clear(), key()_
### Use case of Web Storages
Some use case of Web Storages are
- store data temporarily
- saving products that the user places in his shopping cart
- data can be made available between page requests, multiple browser tabs, and also between browser sessions using localStorage
- can be used offline completely using localStorage
- Web Storage can be a great performance win when some static data is stored on the client to minimize the number of subsequent requests. Even images can be stored in strings using Base64 encoding.
- can be used for user authentication method
For the examples mentioned above, it makes sense to use localStorage. You may be wondering, then, when we should use sessionStorage.
In cases, we want to to get rid of the data as soon as the window is closed. Or, perhaps, if we do not want the application to interfere with the same application thats open in another window. These scenarios are served best with sessionStorage.
Now, let use how use make use of these Web Storage APIs.
## HTML5 Web Storage Objects
HTML web storage provides two objects for storing data on the client:
- window.localStorage - stores data with no expiration date
- window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)Most modern browsers support Web Storage, however it is good to check browser support for localStorage and sessionStorage. Let us see the available methods for the Web Storage objects.
Web Storage objects:
- _localStorage_ - to display the localStorage object
- _localStorage.clear()_ - to remove everything in the local storage
- _localStorage.setItem()_ - to storage data in the localStorage. It takes a key and a value parameters.
- _localStorage.getItem()_ - to display data stored in the localStorage. It takes a key as a parameter.
- _localStorage.removeItem()_ - to remove stored item form a localStorage. It takes key as a parameter.
- _localStorage.key()_ - to display a data stored in a localStorage. It takes index as a parameter.
![local_storage](../images/local_storage.png)
### Setting item to the localStorage
When we set data to be stored in a localStorage, it will be stored as a string. If we are storing an array or an object, we should stringify it first to keep the format unless otherwise we lose the array structure or the object structure of the original data.
We store data in the localStorage using the _localStorage.setItem_ method.
```js
//syntax
localStorage.setItem('key', 'value')
```
- Storing string in a localStorage
```js
localStorage.setItem('firstName', 'Asabeneh') // since the value is string we do not stringify it
console.log(localStorage)
```
```sh
Storage {firstName: 'Asabeneh', length: 1}
```
- Storing number in a local storage
```js
localStorage.setItem('age', 200)
console.log(localStorage)
```
```sh
Storage {age: '200', firstName: 'Asabeneh', length: 2}
```
- Storing an array in a localStorage. If we are storing an array, an object or object array, we should stringify the object first. See the example below.
```js
const skills = ['HTML', 'CSS', 'JS', 'React']
//Skills array has to be stringified first to keep the format.
const skillsJSON = JSON.stringify(skills, undefined, 4)
localStorage.setItem('skills', skillsJSON)
console.log(localStorage)
```
```sh
Storage {age: '200', firstName: 'Asabeneh', skills: 'HTML,CSS,JS,React', length: 3}
```
```js
let skills = [
{ tech: 'HTML', level: 10 },
{ tech: 'CSS', level: 9 },
{ tech: 'JS', level: 8 },
{ tech: 'React', level: 9 },
{ tech: 'Redux', level: 10 },
{ tech: 'Node', level: 8 },
{ tech: 'MongoDB', level: 8 }
]
let skillJSON = JSON.stringify(skills)
localStorage.setItem('skills', skillJSON)
```
- Storing an object in a localStorage. Before we storage objects to a localStorage, the object has to be stringified.
```js
const user = {
firstName: 'Asabeneh',
age: 250,
skills: ['HTML', 'CSS', 'JS', 'React']
}
const userText = JSON.stringify(user, undefined, 4)
localStorage.setItem('user', userText)
```
### Getting item from localStorage
We get data from the local storage using _localStorage.getItem()_ method.
```js
//syntax
localStorage.getItem('key')
```
```js
let firstName = localStorage.getItem('firstName')
let age = localStorage.getItem('age')
let skills = localStorage.getItem('skills')
console.log(firstName, age, skills)
```
```sh
'Asabeneh', '200', '['HTML','CSS','JS','React']'
```
As you can see the skill is in a string format. Let us use JSON.parse() to parse it to normal array.
```js
let skills = localStorage.getItem('skills')
let skillsObj = JSON.parse(skills, undefined, 4)
console.log(skillsObj)
```
```sh
['HTML','CSS','JS','React']
```
### Clearing the localStorage
The clear method, will clear everything stored in the local storage
```js
localStorage.clear()
```
🌕 You are determined .Now, you knew a Web Storages and you knew how to store small data on client browsers. You are 17 steps a head to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
### Exercises: Level 1
1. Store you first name, last name, age, country, city in your browser localStorage.
### Exercises: Level 2
1. Create a student object. The student object will have first name, last name, age, skills, country, enrolled keys and values for the keys. Store the student object in your browser localStorage.
### Exercises: Level 3
1. Create an object 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 also a set of expenses and its description.
🎉 CONGRATULATIONS ! 🎉
[<< Day 16](../16_Day_JSON/16_day_json.md) | [Day 18 >>](../18_Day_Promises/18_day_promises.md)

@ -0,0 +1,272 @@
<div align="center">
<h1> 30 Days Of JavaScript: Promises</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 17](../17_Day_Web_storages/17_day_web_storages.md) | [Day 19>>](../19_Day_Closures/19_day_closures.md)
![Thirty Days Of JavaScript](../images/banners/day_1_18.png)
- [Day 18](#day-18)
- [Promise](#promise)
- [Callbacks](#callbacks)
- [Promise constructor](#promise-constructor)
- [Fetch API](#fetch-api)
- [Async and Await](#async-and-await)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 18
## Promise
We human give or receive a promise to do some activity at some point in time. If we keep the promise we make others happy but if we do not keep the promise, it may lead discontentment. Promise in JavaScript has something in common with the above examples.
A Promise is a way to handle asynchronous operations in JavaScript. It allows handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
A Promise is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation completed successfully.
- rejected: meaning that the operation failed.
A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called. (If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.)
As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained.
## Callbacks
To understand promise very well let us understand callback first. Let's see the following callbacks. From the following code blocks you will notice, the difference between callback and promises.
- call back
Let us see a callback function which can take two parameters. The first parameter is err and the second is result. If the err parameter is false, there will not be error other wise it will return an error.
In this case the err has a value and it will return the err block.
```js
//Callback
const doSomething = callback => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
callback('It did not go well', skills)
}, 2000)
}
const callback = (err, result) => {
if (err) {
return console.log(err)
}
return console.log(result)
}
doSomething(callback)
```
```sh
// after 2 seconds it will print
It did not go well
```
In this case the err is false and it will return the else block which is the result.
```js
const doSomething = callback => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
callback(false, skills)
}, 2000)
}
doSomething((err, result) => {
if (err) {
return console.log(err)
}
return console.log(result)
})
```
```sh
// after 2 seconds it will print the skills
["HTML", "CSS", "JS"]
```
### Promise constructor
We can create a promise using the Promise constructor. We can create a new promise using the key word new followed by the word Promise and followed by a parenthesis. Inside the parenthesis it it takes a callback function. The promise callback function has two parameters which are the *resolve* and *reject* functions.
```js
// syntax
const promise = new Promise((resolve, reject) => {
resolve('success')
reject('failure')
})
```
```js
// Promise
const doPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
if (skills.length > 0) {
resolve(skills)
} else {
reject('Something wrong has happened')
}
}, 2000)
})
doPromise
.then(result => {
console.log(result)
})
.catch(error => console.log(error))
```
```sh
["HTML", "CSS", "JS"]
```
The above promise has been settled with resolve.
Let us another example when the promise is settled with reject.
```js
// Promise
const doPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
if (skills.indexOf('Node') !== -1) {
resolve('fullstack developer')
} else {
reject('Something wrong has happened')
}
}, 2000)
})
doPromise
.then(result => {
console.log(result)
})
.catch(error => console.log(error))
```
```sh
Something wrong has happened
```
## Fetch API
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set. In this challenge we will use fetch to request url and APIS. In addition to that let us see demonstrate use case of promises in accessing network resources using the fetch API.
```js
const url = 'https://restcountries.eu/rest/v2/all' // countries api
fetch(url)
.then(response => response.json()) // accessing the API data as JSON
.then(data => { // getting the data
console.log(data)
})
.catch(error => console.log(error)) // handling error if something wrong happens
```
## Async and Await
Async and await is an elegant way to handle promises. It is easy to understand and it clean to write.
```js
const square = async function (n) {
return n * n
}
square(2)
```
```sh
Promise {<resolved>: 4}
```
The word *async* in front of a function means that function will return a promise. The above square function instead of a value it returned a promise.
How do we access the value from the promise? To access the value from the promise, we will use the keyword *await*.
```js
const square = async function (n) {
return n * n
}
const value = await square(2)
```
```sh
4
```
Now, as you can see from the above example writing async in front of a function create a promise and to get the value from a promise we use await. Async and await go together, one can not exist without the other.
Let us fetch API data using both promise method and async and await method.
- promise
```js
const url = 'https://restcountries.eu/rest/v2/all'
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => console.log(error))
```
- async and await
```js
const fetchData = async () => {
try {
const response = await fetch(url)
const countries = await response.json()
console.log(countries)
} catch (err) {
console.log(err)
}
}
console.log('===== async and await')
fetchData()
```
🌕 You are real and you kept your promise and your reached to day 18. Keep your promise and settle the challenge with resolve. You are 18 steps a head to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises
```js
const countriesAPI = 'https://restcountries.eu/rest/v2/all'
const catsAPI = 'https://api.thecatapi.com/v1/breeds'
```
### Exercises: Level 1
1. Read the countries API using fetch and print the name of country, capital, languages, population and area.
### Exercises: Level 2
1. Print out all the cat names in to catNames variable.
### Exercises: Level 3
1. Read the cats api and find the average weight of cat in metric unit.
2. Read the countries api and find out the 10 largest countries
3. Read the countries api and count total number of languages in the world used as officials.
🎉 CONGRATULATIONS ! 🎉
[<< Day 17](../17_Day_Web_storages/17_day_web_storages.md) | [Day 19>>](../19_Day_Closures/19_day_closures.md)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:18 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:18 Day</h1>
<h2>Promises</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')

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save