Merge 83bd5023e9
into 97f84bf65f
commit
8d3598bcee
@ -0,0 +1,19 @@
|
||||
draft.md
|
||||
playground
|
||||
/playground
|
||||
.DS_Store
|
||||
test.js
|
||||
res.md
|
||||
day3.md
|
||||
day4.md
|
||||
day5.md
|
||||
day6.md
|
||||
day7.md
|
||||
day8.md
|
||||
day9.md
|
||||
day10.md
|
||||
01_02_03_days_backup.md
|
||||
test.md
|
||||
31_Day
|
||||
test.html
|
||||
res.js
|
@ -0,0 +1 @@
|
||||
console.log('Hello, World!')
|
@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>30DaysOfJavaScript:03 Day</h1>
|
||||
<h2>Introduction</h2>
|
||||
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button>
|
||||
<script src="./helloworld.js"></script>
|
||||
<script src="./introduction.js"></script>
|
||||
<script src="./varaible.js"></script>
|
||||
<script src="./main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1 @@
|
||||
console.log('Welcome to 30DaysOfJavaScript')
|
@ -0,0 +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'
|
@ -0,0 +1,17 @@
|
||||
// Declaring different variables of different data types
|
||||
let firstName = 'Asabeneh' // first name of a person
|
||||
let lastName = 'Yetayeh' // last name of a person
|
||||
let country = 'Finland' // country
|
||||
let city = 'Helsinki' // capital city
|
||||
let age = 100 // age in years
|
||||
let isMarried = true
|
||||
|
||||
// Declaring variables with number values
|
||||
const gravity = 9.81 // earth gravity in m/s2
|
||||
const boilingPoint = 100 // water boiling point, temperature in oC
|
||||
const PI = 3.14 // geometrical constant
|
||||
|
||||
// Variables can also be declaring in one line separated by comma
|
||||
let name = 'Asabeneh', //name of a person
|
||||
job = 'teacher',
|
||||
live = 'Finland'
|
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>30DaysOfJavaScript:02 Day</h1>
|
||||
<h2>Data types</h2>
|
||||
|
||||
<!-- import your scripts here -->
|
||||
<script src="./main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1 @@
|
||||
// this is your main.js script
|
After Width: | Height: | Size: 75 KiB |
@ -0,0 +1,34 @@
|
||||
const PI = Math.PI
|
||||
console.log(PI) // 3.141592653589793
|
||||
console.log(Math.round(PI)) // 3; to round values to the nearest number
|
||||
console.log(Math.round(9.81)) // 10
|
||||
console.log(Math.floor(PI)) // 3; rounding down
|
||||
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.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)
|
||||
// Let create random number between 0 to 10
|
||||
const num = Math.floor(Math.random() * 11) // creates random number between 0 and 10
|
||||
console.log(num)
|
||||
|
||||
//Absolute value
|
||||
console.log(Math.abs(-10)) //10
|
||||
//Square root
|
||||
console.log(Math.sqrt(100)) // 10
|
||||
console.log(Math.sqrt(2)) //1.4142135623730951
|
||||
// Power
|
||||
console.log(Math.pow(3, 2)) // 9
|
||||
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
|
||||
|
||||
// Trigonometry
|
||||
console.log(Math.sin(0))
|
||||
console.log(Math.sin(60))
|
||||
console.log(Math.cos(0))
|
||||
console.log(Math.cos(60))
|
@ -0,0 +1,30 @@
|
||||
let nums = [1, 2, 3]
|
||||
nums[0] = 10
|
||||
console.log(nums) // [10, 2, 3]
|
||||
|
||||
let nums = [1, 2, 3]
|
||||
let numbers = [1, 2, 3]
|
||||
console.log(nums == numbers) // false
|
||||
|
||||
let userOne = {
|
||||
name: 'Asabeneh',
|
||||
role: 'teaching',
|
||||
country: 'Finland'
|
||||
}
|
||||
let userTwo = {
|
||||
name: 'Asabeneh',
|
||||
role: 'teaching',
|
||||
country: 'Finland'
|
||||
}
|
||||
console.log(userOne == userTwo) // false
|
||||
|
||||
let numbers = nums
|
||||
console.log(nums == numbers) // true
|
||||
|
||||
let userOne = {
|
||||
name:'Asabeneh',
|
||||
role:'teaching',
|
||||
country:'Finland'
|
||||
}
|
||||
let userTwo = userOne
|
||||
console.log(userOne == userTwo) // true
|
@ -0,0 +1,9 @@
|
||||
let age = 35
|
||||
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
|
||||
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
|
||||
console.log(age, gravity, mass, PI, boilingPoint, bodyTemp)
|
@ -0,0 +1,14 @@
|
||||
let word = 'JavaScript'
|
||||
// we dont' modify string
|
||||
// we don't do like this, word[0] = 'Y'
|
||||
let numOne = 3
|
||||
let numTwo = 3
|
||||
console.log(numOne == numTwo) // true
|
||||
|
||||
let js = 'JavaScript'
|
||||
let py = 'Python'
|
||||
console.log(js == py) //false
|
||||
|
||||
let lightOn = true
|
||||
let lightOff = false
|
||||
console.log(lightOn == lightOff) // false
|
@ -0,0 +1,19 @@
|
||||
// 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'
|
||||
// Concatenating using addition operator
|
||||
let fullName = firstName + space + lastName // concatenation, merging two string together.
|
||||
console.log(fullName)
|
||||
|
||||
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country // ES5
|
||||
console.log(personInfoOne)
|
||||
// Concatenation: Template Literals(Template Strings)
|
||||
let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.` //ES6 - String interpolation method
|
||||
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`
|
||||
console.log(personInfoTwo)
|
||||
console.log(personInfoThree)
|
@ -0,0 +1,7 @@
|
||||
let space = ' ' // an empty space string
|
||||
let firstName = 'Asabeneh'
|
||||
let lastName = 'Yetayeh'
|
||||
let country = 'Finland'
|
||||
let city = 'Helsinki'
|
||||
let language = 'JavaScript'
|
||||
let job = 'teacher'
|
@ -0,0 +1,12 @@
|
||||
// Let us access the first character in 'JavaScript' string.
|
||||
|
||||
let string = 'JavaScript'
|
||||
let firstLetter = string[0]
|
||||
console.log(firstLetter) // J
|
||||
let secondLetter = string[1] // a
|
||||
let thirdLetter = string[2]
|
||||
let lastLetter = string[9]
|
||||
console.log(lastLetter) // t
|
||||
let lastIndex = string.length - 1
|
||||
console.log(lastIndex) // 9
|
||||
console.log(string[lastIndex]) // t
|
@ -0,0 +1,6 @@
|
||||
// charAt(): Takes index and it returns the value at that index
|
||||
string.charAt(index)
|
||||
let string = '30 Days Of JavaScript'
|
||||
console.log(string.charAt(0)) // 3
|
||||
let lastIndex = string.length - 1
|
||||
console.log(string.charAt(lastIndex)) // t
|
@ -0,0 +1,7 @@
|
||||
// charCodeAt(): Takes index and it returns char code(ASCII number) of the value at that index
|
||||
|
||||
string.charCodeAt(index)
|
||||
let string = '30 Days Of JavaScript'
|
||||
console.log(string.charCodeAt(3)) // D ASCII number is 51
|
||||
let lastIndex = string.length - 1
|
||||
console.log(string.charCodeAt(lastIndex)) // t ASCII is 116
|
@ -0,0 +1,6 @@
|
||||
// concat(): it takes many substrings and creates concatenation.
|
||||
// string.concat(substring, substring, substring)
|
||||
let string = '30'
|
||||
console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript
|
||||
let country = 'Fin'
|
||||
console.log(country.concat("land")) // Finland
|
@ -0,0 +1,11 @@
|
||||
// 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).
|
||||
// string.endsWith(substring)
|
||||
let string = 'Love is the best to in this world'
|
||||
console.log(string.endsWith('world')) // true
|
||||
console.log(string.endsWith('love')) // false
|
||||
console.log(string.endsWith('in this world')) // true
|
||||
|
||||
let country = 'Finland'
|
||||
console.log(country.endsWith('land')) // true
|
||||
console.log(country.endsWith('fin')) // false
|
||||
console.log(country.endsWith('Fin')) // false
|
@ -0,0 +1,14 @@
|
||||
// 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.
|
||||
let string = '30 Days Of JavaScript'
|
||||
console.log(string.includes('Days')) // true
|
||||
console.log(string.includes('days')) // false
|
||||
console.log(string.includes('Script')) // true
|
||||
console.log(string.includes('script')) // false
|
||||
console.log(string.includes('java')) // false
|
||||
console.log(string.includes('Java')) // true
|
||||
|
||||
let country = 'Finland'
|
||||
console.log(country.includes('fin')) // false
|
||||
console.log(country.includes('Fin')) // true
|
||||
console.log(country.includes('land')) // true
|
||||
console.log(country.includes('Land')) // false
|
@ -0,0 +1,11 @@
|
||||
// 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
|
||||
|
||||
string.indexOf(substring)
|
||||
let string = '30 Days Of JavaScript'
|
||||
console.log(string.indexOf('D')) // 3
|
||||
console.log(string.indexOf('Days')) // 3
|
||||
console.log(string.indexOf('days')) // -1
|
||||
console.log(string.indexOf('a')) // 4
|
||||
console.log(string.indexOf('JavaScript')) // 11
|
||||
console.log(string.indexOf('Script')) //15
|
||||
console.log(string.indexOf('script')) // -1
|
@ -0,0 +1,6 @@
|
||||
// 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
|
||||
|
||||
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
|
||||
console.log(string.lastIndexOf('love')) // 67
|
||||
console.log(string.lastIndexOf('you')) // 63
|
||||
console.log(string.lastIndexOf('JavaScript')) // 38
|
@ -0,0 +1,6 @@
|
||||
// length: The string length method returns the number of characters in a string included empty space. Example:
|
||||
|
||||
let js = 'JavaScript'
|
||||
console.log(js.length) // 10
|
||||
let firstName = 'Asabeneh'
|
||||
console.log(firstName.length) // 8
|
@ -0,0 +1,22 @@
|
||||
// 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.
|
||||
let string = 'love'
|
||||
let patternOne = /love/ // with out any flag
|
||||
let patternTwo = /love/gi // g-means to search in the whole text, i - case insensitive
|
||||
string.match(substring)
|
||||
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
|
||||
console.log(string.match('love')) //
|
||||
/*
|
||||
output
|
||||
|
||||
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
|
||||
*/
|
||||
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.
|
||||
|
||||
let txt = 'In 2019, I run 30 Days of Pyhton. Now, in 2020 I super exited to start this challenge'
|
||||
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(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
|
||||
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
|
@ -0,0 +1,4 @@
|
||||
// repeat(): it takes a number argument and it returned the repeated version of the string.
|
||||
// string.repeat(n)
|
||||
let string = 'love'
|
||||
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
|
@ -0,0 +1,7 @@
|
||||
// replace(): takes to parameter the old substring and new substring.
|
||||
// string.replace(oldsubstring, newsubstring)
|
||||
|
||||
let string = '30 Days Of JavaScript'
|
||||
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
|
||||
let country = 'Finland'
|
||||
console.log(country.replace('Fin', 'Noman')) // Nomanland
|
@ -0,0 +1,4 @@
|
||||
// search: it takes a substring as an argument and it returns the index of the first match.
|
||||
// string.search(substring)
|
||||
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
|
||||
console.log(string.search('love')) // 2
|
@ -0,0 +1,10 @@
|
||||
// split(): The split method splits a string at a specified place.
|
||||
let string = '30 Days Of JavaScipt'
|
||||
console.log(string.split()) // ["30 Days Of JavaScript"]
|
||||
console.log(string.split(' ')) // ["30", "Days", "Of", "JavaScript"]
|
||||
let firstName = 'Asabeneh'
|
||||
console.log(firstName.split()) // ["Asabeneh"]
|
||||
console.log(firstName.split('')) // ["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(', ')) // ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
|
@ -0,0 +1,11 @@
|
||||
// startsWith: 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).
|
||||
// string.startsWith(substring)
|
||||
let string = 'Love is the best to in this world'
|
||||
console.log(string.startsWith('Love')) // true
|
||||
console.log(string.startsWith('love')) // false
|
||||
console.log(string.startsWith('world')) // false
|
||||
|
||||
let country = 'Finland'
|
||||
console.log(country.startsWith('Fin')) // true
|
||||
console.log(country.startsWith('fin')) // false
|
||||
console.log(country.startsWith('land')) // false
|
@ -0,0 +1,5 @@
|
||||
//substr(): It takes two arguments,the starting index and number of characters to slice.
|
||||
let string = 'JavaScript'
|
||||
console.log(string.substr(4,6)) // Script
|
||||
let country = 'Finland'
|
||||
console.log(country.substr(3, 4)) // land
|
@ -0,0 +1,9 @@
|
||||
// substring(): It takes two arguments,the starting index and the stopping index but it doesn't include the stopping index.
|
||||
let string = 'JavaScript'
|
||||
console.log(string.substring(0,4)) // Java
|
||||
console.log(string.substring(4,10)) // Script
|
||||
console.log(string.substring(4)) // Script
|
||||
let country = 'Finland'
|
||||
console.log(country.substring(0, 3)) // Fin
|
||||
console.log(country.substring(3, 7)) // land
|
||||
console.log(country.substring(3)) // land
|
@ -0,0 +1,7 @@
|
||||
// toLowerCase(): this method changes the string to lowercase letters.
|
||||
let string = 'JavasCript'
|
||||
console.log(string.toLowerCase()) // javascript
|
||||
let firstName = 'Asabeneh'
|
||||
console.log(firstName.toLowerCase()) // asabeneh
|
||||
let country = 'Finland'
|
||||
console.log(country.toLowerCase()) // finland
|
@ -0,0 +1,8 @@
|
||||
// toUpperCase(): this method changes the string to uppercase letters.
|
||||
|
||||
let string = 'JavaScript'
|
||||
console.log(string.toUpperCase()) // JAVASCRIPT
|
||||
let firstName = 'Asabeneh'
|
||||
console.log(firstName.toUpperCase()) // ASABENEH
|
||||
let country = 'Finland'
|
||||
console.log(country.toUpperCase()) // FINLAND
|
@ -0,0 +1,7 @@
|
||||
//trim(): Removes trailing space in the beginning or the end of a string.
|
||||
let string = ' 30 Days Of JavaScript '
|
||||
console.log(string) //
|
||||
console.log(string.trim(' ')) //
|
||||
let firstName = ' Asabeneh '
|
||||
console.log(firstName)
|
||||
console.log(firstName.trim()) //
|
@ -0,0 +1,633 @@
|
||||
<div align="center">
|
||||
<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>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Author:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> January, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 2](../02_Day_Data_types/02_day_data_types.md) | [Day 4 >>](../04_Day_Conditionals/04_day_conditionals.md)
|
||||
|
||||

|
||||
|
||||
- [📔 Day 3](#-day-3)
|
||||
- [Booleans](#booleans)
|
||||
- [Truthy values](#truthy-values)
|
||||
- [Falsy values](#falsy-values)
|
||||
- [Undefined](#undefined)
|
||||
- [Null](#null)
|
||||
- [Operators](#operators)
|
||||
- [Assignment operators](#assignment-operators)
|
||||
- [Arithmetic Operators](#arithmetic-operators)
|
||||
- [Comparison Operators](#comparison-operators)
|
||||
- [Logical Operators](#logical-operators)
|
||||
- [Increment Operator](#increment-operator)
|
||||
- [Decrement Operator](#decrement-operator)
|
||||
- [Ternary Operators](#ternary-operators)
|
||||
- [Operator Precendence](#operator-precendence)
|
||||
- [Window Methods](#window-methods)
|
||||
- [Window alert() method](#window-alert-method)
|
||||
- [Window prompt() method](#window-prompt-method)
|
||||
- [Window confirm() method](#window-confirm-method)
|
||||
- [Date Object](#date-object)
|
||||
- [Creating a time object](#creating-a-time-object)
|
||||
- [Getting full year](#getting-full-year)
|
||||
- [Getting month](#getting-month)
|
||||
- [Getting date](#getting-date)
|
||||
- [Getting day](#getting-day)
|
||||
- [Getting hours](#getting-hours)
|
||||
- [Getting minutes](#getting-minutes)
|
||||
- [Getting seconds](#getting-seconds)
|
||||
- [Getting time](#getting-time)
|
||||
- [💻 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
|
||||
|
||||
## Booleans
|
||||
|
||||
Tipe data boolean mewakili salah satu dari dua nilai: _true_ atau _false_. Nilai Boolean bisa benar atau salah. Penggunaan tipe data ini akan menjadi jelas saat Anda memulai operator perbandingan. Setiap perbandingan mengembalikan nilai boolean yang benar atau salah.
|
||||
|
||||
**Contoh: Nilai Boolean**
|
||||
|
||||
```js
|
||||
let isLightOn = true
|
||||
let isRaining = false
|
||||
let isHungry = false
|
||||
let isMarried = true
|
||||
let truValue = 4 > 3 // true
|
||||
let falseValue = 4 < 3 // false
|
||||
```
|
||||
|
||||
Kami setuju bahwa nilai boolean true atau false.
|
||||
|
||||
### Truthy values
|
||||
|
||||
- Semua angka (positif dan negatif) benar kecuali nol
|
||||
- Semua string benar
|
||||
- Boolean benar
|
||||
|
||||
### Falsy values
|
||||
|
||||
- 0
|
||||
- 0n
|
||||
- null
|
||||
- undefined
|
||||
- NaN
|
||||
- the boolean false
|
||||
- '', "", ``, empty string
|
||||
|
||||
Adalah baik untuk mengingat nilai-nilai kebenaran dan nilai-nilai yang salah itu. Di bagian selanjutnya, kami akan menggunakannya dengan kondisi untuk membuat keputusan.
|
||||
|
||||
## Undefined
|
||||
|
||||
Jika kita mendeklarasikan variabel dan jika kita tidak memberikan nilai, nilainya tidak akan ditentukan. Selain itu, jika suatu fungsi tidak mengembalikan nilainya, itu akan menjadi tidak terdefinisi.
|
||||
|
||||
```js
|
||||
let firstName
|
||||
console.log(firstName) //not defined, because it is not assigned to a value yet
|
||||
```
|
||||
|
||||
## Null
|
||||
|
||||
```js
|
||||
let empty = null
|
||||
console.log(empty) // -> null , means no value
|
||||
```
|
||||
|
||||
## Operators
|
||||
|
||||
### Assignment operators
|
||||
|
||||
Tanda sama dengan di JavaScript adalah operator penugasan. Digunakan untuk menetapkan variabel.
|
||||
|
||||
```js
|
||||
let firstName = 'Asabeneh'
|
||||
let country = 'Finland'
|
||||
```
|
||||
|
||||
Assignment Operators
|
||||
|
||||

|
||||
|
||||
### Arithmetic Operators
|
||||
|
||||
Operator aritmatika adalah operator matematika.
|
||||
|
||||
- Addition(+): a + b
|
||||
- Subtraction(-): a - b
|
||||
- Multiplication(*): a * b
|
||||
- Division(/): a / b
|
||||
- Modulus(%): a % b
|
||||
- Exponential(**): a ** b
|
||||
|
||||
```js
|
||||
let numOne = 4
|
||||
let numTwo = 3
|
||||
let sum = numOne + numTwo
|
||||
let diff = numOne - numTwo
|
||||
let mult = numOne * numTwo
|
||||
let div = numOne / numTwo
|
||||
let remainder = numOne % numTwo
|
||||
let powerOf = numOne ** numTwo
|
||||
|
||||
console.log(sum, diff, mult, div, remainder, powerOf) // 7,1,12,1.33,1, 64
|
||||
|
||||
```
|
||||
|
||||
```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)
|
||||
|
||||
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.
|
||||
The gravity of earth is 9.81 m/s2.
|
||||
*/
|
||||
console.log(
|
||||
`The boiling point of water is ${boilingPoint} oC.\nHuman body temperature is ${bodyTemp} oC.\nThe gravity of earth is ${gravity} m / s2.`
|
||||
)
|
||||
```
|
||||
|
||||
### Comparison Operators
|
||||
|
||||
Dalam pemrograman kami membandingkan nilai, kami menggunakan operator pembanding untuk membandingkan dua nilai. Kami memeriksa apakah suatu nilai lebih besar atau kurang atau sama dengan nilai lain.
|
||||
|
||||

|
||||
**Example: Comparison Operators**
|
||||
|
||||
```js
|
||||
console.log(3 > 2) // true, because 3 is greater than 2
|
||||
console.log(3 >= 2) // true, because 3 is greater than 2
|
||||
console.log(3 < 2) // false, because 3 is greater than 2
|
||||
console.log(2 < 3) // true, because 2 is less than 3
|
||||
console.log(2 <= 3) // true, because 2 is less than 3
|
||||
console.log(3 == 2) // false, because 3 is not equal to 2
|
||||
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) // 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(1 == true) // true, equivalent
|
||||
console.log(1 === true) // false, not exactly the same
|
||||
console.log(undefined == null) // true
|
||||
console.log(undefined === null) // false
|
||||
console.log(NaN == NaN) // false, not equal
|
||||
console.log(NaN === NaN) // false
|
||||
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) // true
|
||||
console.log('milk'.length != 'meat'.length) // false
|
||||
console.log('tomato'.length == 'potato'.length) // true
|
||||
console.log('python'.length > 'dragon'.length) // false
|
||||
```
|
||||
|
||||
Cobalah untuk memahami perbandingan di atas dengan beberapa logika. Mengingat tanpa logika apa pun mungkin sulit.
|
||||
JavaScript adalah sejenis bahasa pemrograman berkabel. Kode JavaScript berjalan dan memberi Anda hasil tetapi kecuali Anda ahli dalam hal itu mungkin bukan hasil yang diinginkan.
|
||||
|
||||
Sebagai aturan praktis, jika suatu nilai tidak benar dengan == maka tidak akan sama dengan ===. Menggunakan === lebih aman daripada menggunakan ==. Pengikut [link](https://dorey.github.io/JavaScript-Equality-Table/) memiliki daftar lengkap perbandingan tipe data.
|
||||
|
||||
### Logical Operators
|
||||
|
||||
Simbol berikut adalah operator logika yang umum:
|
||||
&&(ampersand) , ||(pipe) and !(negation).
|
||||
Operator && menjadi true hanya jika kedua operand benar.
|
||||
The || operator benar, salah satu operan benar.
|
||||
The! operator meniadakan benar menjadi salah dan salah menjadi benar.
|
||||
|
||||
```js
|
||||
// && ampersand operator example
|
||||
|
||||
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
|
||||
|
||||
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 isLightOn = true
|
||||
let isLightOff = !isLightOn // false
|
||||
let isMarried = !false // true
|
||||
```
|
||||
|
||||
### Increment Operator
|
||||
|
||||
Dalam JavaScript kita menggunakan operator increment untuk meningkatkan nilai disimpan dalam variabel. increment bisa jadi increment sebelum atau sesudah. Mari kita lihat masing-masing:
|
||||
|
||||
1. Pre-increment
|
||||
|
||||
```js
|
||||
let count = 0
|
||||
console.log(++count) // 1
|
||||
console.log(count) // 1
|
||||
```
|
||||
|
||||
1. Post-increment
|
||||
|
||||
```js
|
||||
let count = 0
|
||||
console.log(count++) // 0
|
||||
console.log(count) // 1
|
||||
```
|
||||
|
||||
Kami menggunakan sebagian besar waktu post-increment. Setidaknya Anda harus ingat bagaimana menggunakan operator post-increment.
|
||||
|
||||
### Decrement Operator
|
||||
|
||||
Di JavaScript kami menggunakan operator penurunan untuk menurunkan nilai yang disimpan dalam variabel. Penurunan tersebut dapat berupa penurunan sebelum atau sesudah. Mari kita lihat masing-masing:
|
||||
|
||||
1. Pre-decrement
|
||||
|
||||
```js
|
||||
let count = 0
|
||||
console.log(--count) // -1
|
||||
console.log(count) // -1
|
||||
```
|
||||
|
||||
2. Post-decrement
|
||||
|
||||
```js
|
||||
let count = 0
|
||||
console.log(count--) // 0
|
||||
console.log(count) // -1
|
||||
```
|
||||
|
||||
### Ternary Operators
|
||||
|
||||
Operator terner memungkinkan untuk menulis kondisi.
|
||||
Cara lain untuk menulis kondisional menggunakan operator terner. Lihat contoh berikut:
|
||||
|
||||
```js
|
||||
let isRaining = true
|
||||
isRaining
|
||||
? console.log('You need a rain coat.')
|
||||
: console.log('No need for a rain coat.')
|
||||
isRaining = false
|
||||
|
||||
isRaining
|
||||
? console.log('You need a rain coat.')
|
||||
: console.log('No need for a rain coat.')
|
||||
```
|
||||
|
||||
```sh
|
||||
You need a rain coat.
|
||||
No need for a rain coat.
|
||||
```
|
||||
|
||||
```js
|
||||
let number = 5
|
||||
number > 0
|
||||
? console.log(`${number} is a positive number`)
|
||||
: console.log(`${number} is a negative number`)
|
||||
number = -5
|
||||
|
||||
number > 0
|
||||
? console.log(`${number} is a positive number`)
|
||||
: console.log(`${number} is a negative number`)
|
||||
```
|
||||
|
||||
```sh
|
||||
5 is a positive number
|
||||
-5 is a negative number
|
||||
```
|
||||
|
||||
### Operator Precendence
|
||||
|
||||
Saya ingin merekomendasikan Anda untuk membaca tentang prioritas operator dari ini [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
|
||||
|
||||
## Window Methods
|
||||
|
||||
### Window alert() method
|
||||
|
||||
Seperti yang Anda lihat di awal metode alert () menampilkan kotak peringatan dengan pesan tertentu dan tombol OK. Ini adalah metode bawaan dan membutuhkan argumen.
|
||||
|
||||
```js
|
||||
alert(message)
|
||||
```
|
||||
|
||||
```js
|
||||
alert('Welcome to 30DaysOfJavaScript')
|
||||
```
|
||||
|
||||
Jangan gunakan terlalu banyak peringatan karena itu merusak dan mengganggu, gunakan hanya untuk menguji.
|
||||
|
||||
### Window prompt() method
|
||||
|
||||
Metode prompt jendela menampilkan kotak prompt dengan input pada browser Anda untuk mengambil nilai input dan data input dapat disimpan dalam variabel. Metode prompt () membutuhkan dua argumen. Argumen kedua adalah opsional.
|
||||
|
||||
```js
|
||||
prompt('required text', 'optional text')
|
||||
```
|
||||
|
||||
```js
|
||||
let number = prompt('Enter number', 'number goes here')
|
||||
console.log(number)
|
||||
```
|
||||
|
||||
### Window confirm() method
|
||||
|
||||
Metode confirm () menampilkan kotak dialog dengan pesan tertentu, bersama dengan tombol OK dan Batal.
|
||||
Kotak konfirmasi sering digunakan untuk meminta izin dari pengguna untuk mengeksekusi sesuatu. Window confirm () mengambil string sebagai argumen.
|
||||
Mengklik OK menghasilkan nilai sebenarnya, sedangkan mengklik tombol Batal menghasilkan nilai salah.
|
||||
|
||||
```js
|
||||
const agree = confirm('Are you sure you like to delete? ')
|
||||
console.log(agree) // result will be true or false based on what you click on the dialog box
|
||||
```
|
||||
|
||||
Ini tidak semua metode jendela, kita akan memiliki bagian terpisah untuk masuk lebih jauh ke metode jendela.
|
||||
|
||||
## Date Object
|
||||
|
||||
Waktu adalah hal yang penting. Kami ingin mengetahui waktu suatu kegiatan atau acara tertentu. Dalam JavaScript waktu dan tanggal saat ini dibuat menggunakan Objek Tanggal JavaScript. Objek yang kami buat menggunakan objek Tanggal menyediakan banyak metode untuk bekerja dengan tanggal dan waktu. Metode yang kami gunakan untuk mendapatkan informasi tanggal dan waktu dari nilai objek tanggal dimulai dengan kata _get_ karena menyediakan informasi.
|
||||
_getFullYear(), getMonths(), getDate(), getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_
|
||||
|
||||

|
||||
|
||||
### Creating a time object
|
||||
|
||||
Begitu kita membuat objek waktu. Objek waktu akan memberikan informasi tentang waktu. Mari kita buat objek waktu
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now) // Sat Jan 04 2020 00:56:41 GMT+0200 (Eastern European Standard Time)
|
||||
```
|
||||
|
||||
Kami telah membuat objek waktu dan kami dapat mengakses informasi tanggal waktu apa pun dari objek menggunakan metode get yang telah kami sebutkan di tabel.
|
||||
|
||||
### Getting full year
|
||||
|
||||
Mari mengekstrak atau mendapatkan setahun penuh dari objek waktu.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getFullYear()) // 2020
|
||||
```
|
||||
|
||||
### Getting month
|
||||
|
||||
Mari ekstrak atau dapatkan bulan dari objek waktu.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getMonth()) // 0, because the month is January, month(0-11)
|
||||
```
|
||||
|
||||
### Getting date
|
||||
|
||||
Mari mengekstrak atau mendapatkan tanggal bulan dari objek waktu.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getDate()) // 4, because the day of the month is 4th, day(1-31)
|
||||
```
|
||||
|
||||
### Getting day
|
||||
|
||||
Mari kita mengekstrak atau mendapatkan hari dalam seminggu dari objek waktu.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
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)
|
||||
```
|
||||
|
||||
### Getting hours
|
||||
|
||||
Mari kita ekstrak atau dapatkan jam dari objek waktu.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getHours()) // 0, because the time is 00:56:41
|
||||
```
|
||||
|
||||
### Getting minutes
|
||||
|
||||
Mari kita mengekstrak atau mendapatkan menit dari objek waktu.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getMinutes()) // 56, because the time is 00:56:41
|
||||
```
|
||||
|
||||
### Getting seconds
|
||||
|
||||
Mari kita ekstrak atau dapatkan detik dari objek waktu.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getSeconds()) // 41, because the time is 00:56:41
|
||||
```
|
||||
|
||||
### Getting time
|
||||
|
||||
Metode ini memberikan waktu dalam milidetik mulai dari 1 Januari 1970. Ini juga dikenal sebagai waktu Unix. Kita bisa mendapatkan waktu unix dengan dua cara:
|
||||
|
||||
1. Using _getTime()_
|
||||
|
||||
```js
|
||||
const now = new Date() //
|
||||
console.log(now.getTime()) // 1578092201341, this is the number of seconds passed from January 1, 1970 to January 4, 2020 00:56:41
|
||||
```
|
||||
|
||||
1. Using _Date.now()_
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Mari kita format nilai-nilai ini ke dalam format waktu yang dapat dibaca manusia.
|
||||
**Contoh:**
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
const year = now.getFullYear() // return year
|
||||
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
|
||||
```
|
||||
|
||||
🌕 Anda memiliki energi tak terbatas. Anda baru saja menyelesaikan tantangan hari ke-3 dan Anda berada dalam tiga langkah untuk menuju kehebatan. Sekarang lakukan beberapa latihan untuk otak dan otot Anda.
|
||||
|
||||
## 💻 Day 3: Exercises
|
||||
|
||||
### Exercises: Level 1
|
||||
|
||||
1. Deklarasikan firstName, lastName, negara, kota, umur, isMarried, variabel tahun dan tetapkan nilai padanya dan gunakan tipe operator untuk memeriksa tipe data yang berbeda.
|
||||
2. Periksa apakah tipe '10' sama dengan 10
|
||||
3. Periksa apakah parseInt ('9.8') sama dengan 10
|
||||
4. Nilai Boolean bisa benar atau salah.
|
||||
1. Tuliskan tiga pernyataan JavaScript yang memberikan nilai kebenaran.
|
||||
2. Tuliskan tiga pernyataan JavaScript yang memberikan nilai palsu.
|
||||
|
||||
5. Gambarkan hasil ekspresi perbandingan berikut terlebih dahulu tanpa menggunakan console.log (). Setelah Anda memutuskan hasilnya, konfirmasikan menggunakan 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. Cari tahu hasil dari ekspresi berikut terlebih dahulu tanpa menggunakan console.log (). Setelah Anda memutuskan hasilnya, konfirmasikan dengan menggunakan 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
|
||||
|
||||
7. Gunakan objek Tanggal untuk melakukan aktivitas berikut
|
||||
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.
|
||||
|
||||
### Exercises: Level 2
|
||||
|
||||
1. Tulis skrip yang meminta pengguna untuk memasukkan alas dan tinggi segitiga dan menghitung luas segitiga (area = 0.5 x b x h).
|
||||
|
||||
```sh
|
||||
Enter base: 20
|
||||
Enter height: 10
|
||||
The area of the triangle is 50
|
||||
```
|
||||
|
||||
1. Menulis script yang meminta pengguna untuk memasukkan sisi a, sisi b, dan sisi c segitiga dan menghitung keliling segitiga (perimeter = a + b + c)
|
||||
|
||||
```sh
|
||||
Enter side a: 5
|
||||
Enter side b: 4
|
||||
Enter side c: 3
|
||||
The perimeter of the triangle is 12
|
||||
```
|
||||
|
||||
1. Dapatkan panjang dan lebar menggunakan prompt dan hitung luas persegi panjang (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width))
|
||||
1. Dapatkan radius menggunakan prompt dan hitung luas lingkaran (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14.
|
||||
1. Hitung kemiringannya, x-intercept and y-intercept of y = 2x -2
|
||||
1. Slope is (m = y2-y1/x2-x1). Temukan kemiringan di antara titik (2, 2) and point(6,10)
|
||||
1. Bandingkan kemiringan dari dua pertanyaan di atas.
|
||||
1. Hitung nilai y (y = x^2 + 6x + 9). Coba gunakan nilai x yang berbeda dan cari tahu berapa nilai x y adalah 0.
|
||||
1.Tulis skrip yang meminta pengguna memasukkan jam dan tarif per jam. Hitung gaji orang tersebut? Tulis skrip yang meminta pengguna memasukkan jam dan tarif per jam. Hitung gaji orang tersebut?
|
||||
|
||||
```sh
|
||||
Enter hours: 40
|
||||
Enter rate per hour: 28
|
||||
Your weekly earning is 1120
|
||||
```
|
||||
|
||||
1. Jika panjang nama Anda lebih dari 7 ucapkan, nama Anda panjang, atau nama Anda pendek.
|
||||
1. Bandingkan panjang nama depan Anda dan panjang nama keluarga Anda dan Anda akan mendapatkan keluaran ini.
|
||||
|
||||
```js
|
||||
let firstName = 'Asabeneh'
|
||||
let lastName = 'Yetayeh'
|
||||
```
|
||||
|
||||
```sh
|
||||
Your first name, Asabeneh is longer than your family name, Yetayeh
|
||||
```
|
||||
|
||||
1. Deklarasikan dua variabel _myAge_ dan _yourAge_ dan berikan nilai awal serta myAge dan yourAge.
|
||||
|
||||
```js
|
||||
let myAge = 250
|
||||
let yourAge = 25
|
||||
```
|
||||
|
||||
```sh
|
||||
I am 225 years older than you.
|
||||
```
|
||||
|
||||
1. Menggunakan prompt, dapatkan tahun kelahiran pengguna dan jika pengguna berusia 18 tahun ke atas, izinkan pengguna mengemudi jika tidak, beri tahu pengguna untuk menunggu selama beberapa tahun.
|
||||
|
||||
```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. Tulis skrip yang meminta pengguna memasukkan jumlah tahun. Hitung berapa detik seseorang bisa hidup. Asumsikan seseorang hidup hanya seratus tahun
|
||||
|
||||
```sh
|
||||
Enter number of yours you live: 100
|
||||
You lived 3153600000 seconds.
|
||||
```
|
||||
|
||||
1. Buat format waktu yang dapat dibaca manusia menggunakan objek Tanggal waktu
|
||||
1. YYYY-MM-DD HH:mm
|
||||
2. DD-MM-YYYY HH:mm
|
||||
3. DD/MM/YYYY HH:mm
|
||||
|
||||
### Exercises: Level 3
|
||||
|
||||
1. Buat format waktu yang dapat dibaca manusia menggunakan objek Tanggal waktu. Jam dan menit harus sepanjang waktu dua digit (7 jam harus 07 dan 5 menit harus 05)
|
||||
1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05
|
||||
|
||||
[<< Day 2](../02_Day_Data_types/02_day_data_types.md) | [Day 4 >>](../04_Day_Conditionals/04_day_conditionals.md)
|
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript: 03 Day</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>30DaysOfJavaScript:03 Day</h1>
|
||||
<h2>Booleans, undefined, null, date object</h2>
|
||||
|
||||
<!-- import your scripts here -->
|
||||
<script src="./scripts/main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1 @@
|
||||
// this is your main.js script
|
@ -0,0 +1,376 @@
|
||||
<div align="center">
|
||||
<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>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Author:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> January, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 3](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) | [Day 5 >>](../05_Day_Arrays/05_day_arrays.md)
|
||||
|
||||

|
||||
|
||||
- [📔 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)
|
||||
- [💻 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 for 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
|
||||
- Repetitive execution: a block of one or more statements will be repetitively executed as long as a certain expression is true. In this section, we will cover _if_, _else_ , _else if_ statements. The comparison and logical operators we learned in the previous sections will be useful in here.
|
||||
|
||||
Conditions can be implementing using the following ways:
|
||||
|
||||
- if
|
||||
- if else
|
||||
- if else if else
|
||||
- switch
|
||||
- ternary operator
|
||||
|
||||
### If
|
||||
|
||||
In JavaScript and other programming languages the key word _if_ is to used 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
|
||||
if (condition) {
|
||||
//this part of code runs for truthy condition
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```js
|
||||
let num = 3
|
||||
if (num > 0) {
|
||||
console.log(`${num} is a positive number`)
|
||||
}
|
||||
// 3 is a positive number
|
||||
```
|
||||
|
||||
As you can see in the condition example above, 3 is greater than 0, so it is a positive number. The condition was true and the block of code was executed. However, if the condition is false, we won't see any results.
|
||||
|
||||
```js
|
||||
let isRaining = true
|
||||
if (isRaining) {
|
||||
console.log('Remember to take your rain coat.')
|
||||
}
|
||||
```
|
||||
|
||||
The same goes for the second condition, if isRaining is false the if block will not be executed and we do not see any output. In order to see the result of a falsy condition, we should have another block, which is going to be _else_.
|
||||
|
||||
### If Else
|
||||
|
||||
If condition is true the first block will be executed, if not the else condition will be executed.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
if (condition) {
|
||||
// this part of code runs for truthy condition
|
||||
} else {
|
||||
// this part of code runs for false condition
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
let num = 3
|
||||
if (num > 0) {
|
||||
console.log(`${num} is a positive number`)
|
||||
} else {
|
||||
console.log(`${num} is a negative number`)
|
||||
}
|
||||
// 3 is a positive number
|
||||
|
||||
num = -3
|
||||
if (num > 0) {
|
||||
console.log(`${num} is a positive number`)
|
||||
} else {
|
||||
console.log(`${num} is a negative number`)
|
||||
}
|
||||
// -3 is a negative number
|
||||
```
|
||||
|
||||
```js
|
||||
let isRaining = true
|
||||
if (isRaining) {
|
||||
console.log('You need a rain coat.')
|
||||
} else {
|
||||
console.log('No need for a rain coat.')
|
||||
}
|
||||
// You need a rain coat.
|
||||
|
||||
isRaining = false
|
||||
if (isRaining) {
|
||||
console.log('You need a rain coat.')
|
||||
} else {
|
||||
console.log('No need for a rain coat.')
|
||||
}
|
||||
// No need for a rain coat.
|
||||
```
|
||||
|
||||
The last condition is false, therefore the else block was executed. What if we have more than two conditions? In that case, we would use *else if* conditions.
|
||||
|
||||
### If Else if Else
|
||||
|
||||
On our daily life, we make decisions on daily basis. We make decisions 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
|
||||
if (condition) {
|
||||
// code
|
||||
} else if (condition) {
|
||||
// code
|
||||
} else {
|
||||
// code
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```js
|
||||
let a = 0
|
||||
if (a > 0) {
|
||||
console.log(`${a} is a positive number`)
|
||||
} else if (a < 0) {
|
||||
console.log(`${a} is a negative number`)
|
||||
} else if (a == 0) {
|
||||
console.log(`${a} is zero`)
|
||||
} else {
|
||||
console.log(`${a} is not a number`)
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// if else if else
|
||||
let weather = 'sunny'
|
||||
if (weather === 'rainy') {
|
||||
console.log('You need a rain coat.')
|
||||
} else if (weather === 'cloudy') {
|
||||
console.log('It might be cold, you need a jacket.')
|
||||
} else if (weather === 'sunny') {
|
||||
console.log('Go out freely.')
|
||||
} else {
|
||||
console.log('No need for rain coat.')
|
||||
}
|
||||
```
|
||||
|
||||
### Switch
|
||||
|
||||
Switch is an alternative for **if else if else else**.
|
||||
The switch statement starts with a *switch* keyword followed by a parenthesis and code block. Inside the code block we will have different cases. Case block runs if the value in the switch statement parenthesis matches with the case value. The break statement is to terminate execution so the code execution does not go down after the condition is satisfied. The default block runs if all the cases don't satisfy the condition.
|
||||
|
||||
```js
|
||||
switch(caseValue){
|
||||
case 1:
|
||||
// code
|
||||
break
|
||||
case 2:
|
||||
// code
|
||||
break
|
||||
case 3:
|
||||
// code
|
||||
default:
|
||||
// code
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
let weather = 'cloudy'
|
||||
switch (weather) {
|
||||
case 'rainy':
|
||||
console.log('You need a rain coat.')
|
||||
break
|
||||
case 'cloudy':
|
||||
console.log('It might be cold, you need a jacket.')
|
||||
break
|
||||
case 'sunny':
|
||||
console.log('Go out freely.')
|
||||
break
|
||||
default:
|
||||
console.log(' No need for rain coat.')
|
||||
}
|
||||
|
||||
// Switch More Examples
|
||||
let dayUserInput = prompt('What day is today ?')
|
||||
let day = dayUserInput.toLowerCase()
|
||||
|
||||
switch (day) {
|
||||
case 'monday':
|
||||
console.log('Today is Monday')
|
||||
break
|
||||
case 'tuesday':
|
||||
console.log('Today is Tuesday')
|
||||
break
|
||||
case 'wednesday':
|
||||
console.log('Today is Wednesday')
|
||||
break
|
||||
case 'thursday':
|
||||
console.log('Today is Thursday')
|
||||
break
|
||||
case 'friday':
|
||||
console.log('Today is Friday')
|
||||
break
|
||||
case 'saturday':
|
||||
console.log('Today is Saturday')
|
||||
break
|
||||
case 'sunday':
|
||||
console.log('Today is Sunday')
|
||||
break
|
||||
default:
|
||||
console.log('It is not a week 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.
|
||||
|
||||
```js
|
||||
let isRaining = true
|
||||
isRaining
|
||||
? console.log('You need a rain coat.')
|
||||
: console.log('No need for a rain coat.')
|
||||
```
|
||||
|
||||
🌕 You are extraordinary and you have a remarkable potential. You have just completed day 4 challenges and you are four steps ahead to your way to greatness. Now do some exercises for your brain and muscle.
|
||||
|
||||
## 💻 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 another feedback stating to wait for the number of years he neds to turn 18.
|
||||
|
||||
```sh
|
||||
Enter your age: 30
|
||||
You are old enough to drive.
|
||||
|
||||
Enter your age:15
|
||||
You are left with 3 years to drive.
|
||||
```
|
||||
|
||||
1. Compare the values of myAge and yourAge using if … else. Based on the comparison and log the result to console stating who is older (me or you). Use prompt(“Enter your age:”) to get the age as input.
|
||||
|
||||
```sh
|
||||
Enter your age: 30
|
||||
You are 5 years older than me.
|
||||
```
|
||||
|
||||
1. If a is greater than b return 'a is greater than b' else 'a is less than b'. Try to implement it in to ways
|
||||
|
||||
- using if else
|
||||
- ternary operator.
|
||||
|
||||
```js
|
||||
let a = 4
|
||||
let b = 3
|
||||
```
|
||||
|
||||
```sh
|
||||
4 is greater than 3
|
||||
```
|
||||
|
||||
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
|
||||
Enter a number: 2
|
||||
2 is an even number
|
||||
|
||||
Enter a number: 9
|
||||
9 is is an odd number.
|
||||
```
|
||||
|
||||
### Exercises: Level 2
|
||||
|
||||
1. Write a code which can give grades 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 today? Saturday
|
||||
Saturday is a weekend.
|
||||
|
||||
What is the day today? saturDaY
|
||||
Saturday is a weekend.
|
||||
|
||||
What is the day today? Friday
|
||||
Friday is a working day.
|
||||
|
||||
What is the day today? FrIDAy
|
||||
Friday is a working day.
|
||||
```
|
||||
|
||||
### Exercises: Level 3
|
||||
|
||||
1. Write a program which tells the number of days in a month.
|
||||
|
||||
```sh
|
||||
Enter a month: January
|
||||
January has 31 days.
|
||||
|
||||
Enter a month: JANUARY
|
||||
January has 31 day
|
||||
|
||||
Enter a month: February
|
||||
February has 28 days.
|
||||
|
||||
Enter a month: FEbruary
|
||||
February has 28 days.
|
||||
```
|
||||
|
||||
1. Write a program which tells the number of days in a month, now consider leap year.
|
||||
|
||||
|
||||
🎉 CONGRATULATIONS ! 🎉
|
||||
|
||||
[<< Day 3](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) | [Day 5 >>](../05_Day_Arrays/05_day_arrays.md)
|
@ -0,0 +1,15 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<!-- import your scripts here -->
|
||||
<script src="./scripts/main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1,3 @@
|
||||
// this is your main.js script
|
||||
|
||||
alert('Open the browser console whenever you work on JavaScript')
|
@ -0,0 +1,779 @@
|
||||
<div align="center">
|
||||
<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>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Author:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> January, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 4](../04_Day_Conditionals/04_day_Conditionals.md) | [Day 6 >>](../06_Day_Loops/06_day_loops.md)
|
||||
|
||||

|
||||
|
||||
- [📔 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)
|
||||
- [Creating an array using split](#creating-an-array-using-split)
|
||||
- [Accessing array items using index](#accessing-array-items-using-index)
|
||||
- [Modifying array element](#modifying-array-element)
|
||||
- [Methods to manipulate array](#methods-to-manipulate-array)
|
||||
- [Array Constructor](#array-constructor)
|
||||
- [Creating static values with fill](#creating-static-values-with-fill)
|
||||
- [Concatenating array using concat](#concatenating-array-using-concat)
|
||||
- [Getting array length](#getting-array-length)
|
||||
- [Getting index an element in arr array](#getting-index-an-element-in-arr-array)
|
||||
- [Getting last index of an element in array](#getting-last-index-of-an-element-in-array)
|
||||
- [Checking array](#checking-array)
|
||||
- [Converting array to string](#converting-array-to-string)
|
||||
- [Joining array elements](#joining-array-elements)
|
||||
- [Slice array elements](#slice-array-elements)
|
||||
- [Splice method in array](#splice-method-in-array)
|
||||
- [Adding item to an array using push](#adding-item-to-an-array-using-push)
|
||||
- [Removing the end element using pop](#removing-the-end-element-using-pop)
|
||||
- [Removing an element from the beginning](#removing-an-element-from-the-beginning)
|
||||
- [Add an element from the beginning](#add-an-element-from-the-beginning)
|
||||
- [Reversing array order](#reversing-array-order)
|
||||
- [Sorting elements in array](#sorting-elements-in-array)
|
||||
- [Array of arrays](#array-of-arrays)
|
||||
- [💻 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 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 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
|
||||
|
||||
```js
|
||||
// syntax
|
||||
const arr = Array()
|
||||
// or
|
||||
// let arr = new Array()
|
||||
console.log(arr) // []
|
||||
```
|
||||
|
||||
- Using square brackets([])
|
||||
|
||||
```js
|
||||
// syntax
|
||||
// This the most recommended way to create an empty list
|
||||
const arr = []
|
||||
console.log(arr)
|
||||
```
|
||||
|
||||
### How to create an array with values
|
||||
|
||||
Array with initial values. We use _length_ property to find the length of an array.
|
||||
|
||||
```js
|
||||
const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // array of numbers
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of strings, fruits
|
||||
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of strings, vegetables
|
||||
const animalProducts = ['milk', 'meat', 'butter', 'yoghurt'] // array of strings, products
|
||||
const webTechs = ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] // array of web technologies
|
||||
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] // array of strings, countries
|
||||
|
||||
// Print the array and its length
|
||||
|
||||
console.log('Numbers:', numbers)
|
||||
console.log('Number of numbers:', numbers.length)
|
||||
|
||||
console.log('Fruits:', fruits)
|
||||
console.log('Number of fruits:', fruits.length)
|
||||
|
||||
console.log('Vegetables:', vegetables)
|
||||
console.log('Number of vegetables:', vegetables.length)
|
||||
|
||||
console.log('Animal products:', animalProducts)
|
||||
console.log('Number of animal products:', animalProducts.length)
|
||||
|
||||
console.log('Web technologies:', webTechs)
|
||||
console.log('Number of web technologies:', webTechs.length)
|
||||
|
||||
console.log('Countries:', countries)
|
||||
console.log('Number of countries:', countries.length)
|
||||
```
|
||||
|
||||
```sh
|
||||
Numbers: [0, 3.14, 9.81, 37, 98.6, 100]
|
||||
Number of numbers: 6
|
||||
Fruits: ['banana', 'orange', 'mango', 'lemon']
|
||||
Number of fruits: 4
|
||||
Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
|
||||
Number of vegetables: 5
|
||||
Animal products: ['milk', 'meat', 'butter', 'yoghurt']
|
||||
Number of animal products: 4
|
||||
Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB']
|
||||
Number of web technologies: 7
|
||||
Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
|
||||
Number of countries: 5
|
||||
```
|
||||
|
||||
- Array can have items of different data types
|
||||
|
||||
```js
|
||||
const arr = [
|
||||
'Asabeneh',
|
||||
250,
|
||||
true,
|
||||
{ country: 'Finland', city: 'Helsinki' },
|
||||
{ skills: ['HTML', 'CSS', 'JS', 'React', 'Python'] }
|
||||
] // arr containing different data types
|
||||
console.log(arr)
|
||||
```
|
||||
|
||||
### Creating an array using split
|
||||
|
||||
As we have seen in the earlier section, we can split a string at different positions, and we can change to an array. Let us see the examples below.
|
||||
|
||||
```js
|
||||
let js = 'JavaScript'
|
||||
const charsInJavaScript = js.split('')
|
||||
|
||||
console.log(charsInJavaScript) // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]
|
||||
|
||||
let companiesString = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon'
|
||||
const companies = companiesString.split(',')
|
||||
|
||||
console.log(companies) // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"]
|
||||
let txt =
|
||||
'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
|
||||
const words = txt.split(' ')
|
||||
|
||||
console.log(words)
|
||||
// the text has special characters think how you can just get only the words
|
||||
// ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"]
|
||||
```
|
||||
|
||||
### 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 index of each element in the array.
|
||||
|
||||

|
||||
|
||||
```js
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon']
|
||||
let firstFruit = fruits[0] // we are accessing the first item using its index
|
||||
|
||||
console.log(firstFruit) // banana
|
||||
|
||||
secondFruit = fruits[1]
|
||||
console.log(secondFruit) // orange
|
||||
|
||||
let lastFruit = fruits[3]
|
||||
console.log(lastFruit) // lemon
|
||||
// Last index can be calculated as follows
|
||||
|
||||
let lastIndex = fruits.length - 1
|
||||
lastFruit = fruits[lastIndex]
|
||||
|
||||
console.log(lastFruit) // lemon
|
||||
```
|
||||
|
||||
```js
|
||||
const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // set of numbers
|
||||
|
||||
console.log(numbers.length) // => to know the size of the array, which is 6
|
||||
console.log(numbers) // -> [0, 3.14, 9.81, 37, 98.6, 100]
|
||||
console.log(numbers[0]) // -> 0
|
||||
console.log(numbers[5]) // -> 100
|
||||
|
||||
let lastIndex = numbers.length - 1;
|
||||
console.log(numbers[lastIndex]) // -> 100
|
||||
```
|
||||
|
||||
```js
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
] // List of web technologies
|
||||
|
||||
console.log(webTechs) // all the array items
|
||||
console.log(webTechs.length) // => to know the size of the array, which is 7
|
||||
console.log(webTechs[0]) // -> HTML
|
||||
console.log(webTechs[6]) // -> MongoDB
|
||||
|
||||
let lastIndex = webTechs.length - 1
|
||||
console.log(webTechs[lastIndex]) // -> MongoDB
|
||||
```
|
||||
|
||||
```js
|
||||
const countries = [
|
||||
'Albania',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya'
|
||||
] // List of countries
|
||||
|
||||
console.log(countries) // -> all countries in array
|
||||
console.log(countries[0]) // -> Albania
|
||||
console.log(countries[10]) // -> Kenya
|
||||
|
||||
let lastIndex = countries.length - 1;
|
||||
console.log(countries[lastIndex]) // -> Kenya
|
||||
```
|
||||
|
||||
```js
|
||||
const shoppingCart = [
|
||||
'Milk',
|
||||
'Mango',
|
||||
'Tomato',
|
||||
'Potato',
|
||||
'Avocado',
|
||||
'Meat',
|
||||
'Eggs',
|
||||
'Sugar'
|
||||
] // List of food products
|
||||
|
||||
console.log(shoppingCart) // -> all shoppingCart in array
|
||||
console.log(shoppingCart[0]) // -> Milk
|
||||
console.log(shoppingCart[7]) // -> Sugar
|
||||
|
||||
let lastIndex = shoppingCart.length - 1;
|
||||
console.log(shoppingCart[lastIndex]) // -> Sugar
|
||||
```
|
||||
|
||||
### Modifying array element
|
||||
|
||||
An array is mutable(modifiable). Once an array is created, we can modify the contents of the array elements.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers[0] = 10 // changing 1 at index 0 to 10
|
||||
numbers[1] = 20 // changing 2 at index 1 to 20
|
||||
|
||||
console.log(numbers) // [10, 20, 3, 4, 5]
|
||||
|
||||
const countries = [
|
||||
'Albania',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya'
|
||||
]
|
||||
|
||||
countries[0] = 'Afghanistan' // Replacing Albania by Afghanistan
|
||||
let lastIndex = countries.length - 1
|
||||
countries[lastIndex] = 'Korea' // Replacing Kenya by Korea
|
||||
|
||||
console.log(countries)
|
||||
```
|
||||
|
||||
```sh
|
||||
["Afghanistan", "Bolivia", "Canada", "Denmark", "Ethiopia", "Finland", "Germany", "Hungary", "Ireland", "Japan", "Korea"]
|
||||
```
|
||||
|
||||
### Methods to manipulate array
|
||||
|
||||
There are different methods to manipulate an array. These are some of the available methods to deal with arrays:_Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift_
|
||||
|
||||
#### Array Constructor
|
||||
|
||||
Array:To create an array.
|
||||
|
||||
```js
|
||||
const arr = Array() // creates an an empty array
|
||||
console.log(arr)
|
||||
|
||||
const eightEmptyValues = Array(8) // it creates eight empty values
|
||||
console.log(eightEmptyValues) // [empty x 8]
|
||||
```
|
||||
|
||||
#### Creating static values with fill
|
||||
|
||||
fill: Fill all the array elements with a static value
|
||||
|
||||
```js
|
||||
const arr = Array() // creates an an empty array
|
||||
console.log(arr)
|
||||
|
||||
const eightXvalues = Array(8).fill('X') // it creates eight element values filled with 'X'
|
||||
console.log(eightXvalues) // ['X', 'X','X','X','X','X','X','X']
|
||||
|
||||
const eight0values = Array(8).fill(0) // it creates eight element values filled with '0'
|
||||
console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0]
|
||||
|
||||
const four4values = Array(4).fill(4) // it creates 4 element values filled with '4'
|
||||
console.log(four4values) // [4, 4, 4, 4]
|
||||
```
|
||||
|
||||
#### Concatenating array using concat
|
||||
|
||||
concat:To concatenate two arrays.
|
||||
|
||||
```js
|
||||
const firstList = [1, 2, 3]
|
||||
const secondList = [4, 5, 6]
|
||||
const thirdList = firstList.concat(secondList)
|
||||
|
||||
console.log(thirdList) // [1, 2, 3, 4, 5, 6]
|
||||
```
|
||||
|
||||
```js
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of fruits
|
||||
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of vegetables
|
||||
const fruitsAndVegetables = fruits.concat(vegetables) // concatenate the two arrays
|
||||
|
||||
console.log(fruitsAndVegetables)
|
||||
```
|
||||
|
||||
```sh
|
||||
["banana", "orange", "mango", "lemon", "Tomato", "Potato", "Cabbage", "Onion", "Carrot"]
|
||||
```
|
||||
|
||||
#### Getting array length
|
||||
|
||||
Length:To know the size of the array
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
console.log(numbers.length) // -> 5 is the size of the array
|
||||
```
|
||||
|
||||
#### Getting index an element in arr array
|
||||
|
||||
indexOf:To check if an item exist in an array. If it exists it returns the index else it returns -1.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
console.log(numbers.indexOf(5)) // -> 4
|
||||
console.log(numbers.indexOf(0)) // -> -1
|
||||
console.log(numbers.indexOf(1)) // -> 0
|
||||
console.log(numbers.indexOf(6)) // -> -1
|
||||
```
|
||||
|
||||
Check an element if it exist in an array.
|
||||
|
||||
- Check items in a list
|
||||
|
||||
```js
|
||||
// let us check if a banana exist in the array
|
||||
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon']
|
||||
let index = fruits.indexOf('banana') // 0
|
||||
|
||||
if(index != -1){
|
||||
console.log('This fruit does exist in the array')
|
||||
} else {
|
||||
console.log('This fruit does not exist in the array')
|
||||
}
|
||||
// This fruit does exist in the array
|
||||
|
||||
// we can use also ternary here
|
||||
index != -1 ? console.log('This fruit does exist in the array'): console.log('This fruit does not exist in the array')
|
||||
|
||||
// let us check if a avocado exist in the array
|
||||
let indexOfAvocado = fruits.indexOf('avocado') // -1, if the element not found index is -1
|
||||
if(indexOfAvocado!= -1){
|
||||
console.log('This fruit does exist in the array')
|
||||
} else {
|
||||
console.log('This fruit does not exist in the array')
|
||||
}
|
||||
// This fruit does not exist in the array
|
||||
```
|
||||
|
||||
#### Getting last index of an element in array
|
||||
|
||||
lastIndexOf: It gives the position of the last item in the array. If it exist, it returns the index else it returns -1.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5, 3, 1, 2]
|
||||
|
||||
console.log(numbers.lastIndexOf(2)) // 7
|
||||
console.log(numbers.lastIndexOf(0)) // -1
|
||||
console.log(numbers.lastIndexOf(1)) // 6
|
||||
console.log(numbers.lastIndexOf(4)) // 3
|
||||
console.log(numbers.lastIndexOf(6)) // -1
|
||||
```
|
||||
|
||||
includes:To check if an item exist in an array. If it exist it returns the true else it returns false.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
console.log(numbers.includes(5)) // true
|
||||
console.log(numbers.includes(0)) // false
|
||||
console.log(numbers.includes(1)) // true
|
||||
console.log(numbers.includes(6)) // false
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
] // List of web technologies
|
||||
|
||||
console.log(webTechs.includes('Node')) // true
|
||||
console.log(webTechs.includes('C')) // false
|
||||
```
|
||||
|
||||
#### Checking array
|
||||
|
||||
Array.isArray:To check if the data type is an array
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
console.log(Array.isArray(numbers)) // true
|
||||
|
||||
const number = 100
|
||||
console.log(Array.isArray(number)) // false
|
||||
```
|
||||
|
||||
#### Converting array to string
|
||||
|
||||
toString:Converts array to string
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
console.log(numbers.toString()) // 1,2,3,4,5
|
||||
|
||||
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
|
||||
console.log(names.toString()) // Asabeneh,Mathias,Elias,Brook
|
||||
```
|
||||
|
||||
#### Joining array elements
|
||||
|
||||
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]
|
||||
console.log(numbers.join()) // 1,2,3,4,5
|
||||
|
||||
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
|
||||
|
||||
console.log(names.join()) // Asabeneh,Mathias,Elias,Brook
|
||||
console.log(names.join('')) //AsabenehMathiasEliasBrook
|
||||
console.log(names.join(' ')) //Asabeneh Mathias Elias Brook
|
||||
console.log(names.join(', ')) //Asabeneh, Mathias, Elias, Brook
|
||||
console.log(names.join(' # ')) //Asabeneh # Mathias # Elias # Brook
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
] // List of web technologies
|
||||
|
||||
console.log(webTechs.join()) // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB"
|
||||
console.log(webTechs.join(' # ')) // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB"
|
||||
```
|
||||
|
||||
#### Slice array elements
|
||||
|
||||
Slice: To cut out a multiple items in range. It takes two parameters:starting and ending position. It doesn't include the ending position.
|
||||
|
||||
```js
|
||||
const numbers = [1,2,3,4,5]
|
||||
|
||||
console.log(numbers.slice()) // -> it copies all item
|
||||
console.log(numbers.slice(0)) // -> it copies all item
|
||||
console.log(numbers.slice(0, numbers.length)) // it copies all item
|
||||
console.log(numbers.slice(1,4)) // -> [2,3,4] // it doesn't include the ending position
|
||||
```
|
||||
|
||||
#### Splice method in array
|
||||
|
||||
Splice: It takes three parameters:Starting position, number of times to be removed and number of items to be added.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
console.log(numbers.splice()) // -> remove all items
|
||||
|
||||
```
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
console.log(numbers.splice(0,1)) // remove the first item
|
||||
```
|
||||
|
||||
```js
|
||||
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
|
||||
|
||||
Push: adding item in the end. To add item to the end of an existing array we use the push method.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
const arr = ['item1', 'item2','item3']
|
||||
arr.push('new item')
|
||||
|
||||
console.log(arr)
|
||||
// ['item1', 'item2','item3','new item']
|
||||
```
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.push(6)
|
||||
|
||||
console.log(numbers) // -> [1,2,3,4,5,6]
|
||||
|
||||
numbers.pop() // -> remove one item from the end
|
||||
console.log(numbers) // -> [1,2,3,4,5]
|
||||
```
|
||||
|
||||
```js
|
||||
let fruits = ['banana', 'orange', 'mango', 'lemon']
|
||||
fruits.push('apple')
|
||||
|
||||
console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple']
|
||||
|
||||
fruits.push('lime')
|
||||
console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']
|
||||
```
|
||||
|
||||
#### Removing the end element using pop
|
||||
|
||||
pop: Removing item in the end.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.pop() // -> remove one item from the end
|
||||
|
||||
console.log(numbers) // -> [1,2,3,4]
|
||||
```
|
||||
|
||||
#### Removing an element from the beginning
|
||||
|
||||
shift: Removing one array element in the beginning of the array.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.shift() // -> remove one item from the beginning
|
||||
|
||||
console.log(numbers) // -> [2,3,4,5]
|
||||
```
|
||||
|
||||
#### Add an element from the beginning
|
||||
|
||||
unshift: Adding array element in the beginning of the array.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.unshift(0) // -> add one item from the beginning
|
||||
|
||||
console.log(numbers) // -> [0,1,2,3,4,5]
|
||||
```
|
||||
|
||||
#### Reversing array order
|
||||
|
||||
reverse: reverse the order of an array.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.reverse() // -> reverse array order
|
||||
|
||||
console.log(numbers) // [5, 4, 3, 2, 1]
|
||||
|
||||
numbers.reverse()
|
||||
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 a call back function in the coming sections.
|
||||
|
||||
```js
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
]
|
||||
|
||||
webTechs.sort()
|
||||
console.log(webTechs) // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"]
|
||||
|
||||
webTechs.reverse() // after sorting we can reverse it
|
||||
console.log(webTechs) // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"]
|
||||
```
|
||||
|
||||
### Array of arrays
|
||||
|
||||
Array can store different data types including an array itself. Let us create an array of arrays
|
||||
|
||||
```js
|
||||
const firstNums = [1, 2, 3]
|
||||
const secondNums = [1, 4, 9]
|
||||
|
||||
const arrayOfArray = [[1, 2, 3], [1, 2, 3]]
|
||||
console.log(arrayOfArray[0]) // [1, 2, 3]
|
||||
|
||||
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
|
||||
const backEnd = ['Node','Express', 'MongoDB']
|
||||
const fullStack = [frontEnd, backEnd]
|
||||
console.log(fullStack) // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]]
|
||||
console.log(fullStack.length) // 2
|
||||
console.log(fullStack[0]) // ["HTML", "CSS", "JS", "React", "Redux"]
|
||||
console.log(fullStack[1]) // ["Node", "Express", "MongoDB"]
|
||||
```
|
||||
|
||||
🌕 You are diligent and you have already achieved quite a lot. You have just completed day 5 challenges and you are 5 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## 💻 Exercise
|
||||
|
||||
### Exercise: Level 1
|
||||
|
||||
```js
|
||||
const countries = [
|
||||
'Albania',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya'
|
||||
]
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
]
|
||||
```
|
||||
|
||||
1. Declare an _empty_ 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 =
|
||||
'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
|
||||
console.log(words)
|
||||
console.log(words.length)
|
||||
```
|
||||
|
||||
```sh
|
||||
["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"]
|
||||
|
||||
13
|
||||
```
|
||||
|
||||
1. In the following shopping cart add, remove, edit items
|
||||
|
||||
```js
|
||||
const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey']
|
||||
```
|
||||
|
||||
- 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.
|
||||
|
||||
```js
|
||||
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
|
||||
const backEnd = ['Node','Express', 'MongoDB']
|
||||
|
||||
console.log(fullStack)
|
||||
```
|
||||
|
||||
```sh
|
||||
["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]
|
||||
```
|
||||
|
||||
### Exercise: Level 3
|
||||
|
||||
1. The following is an array of 10 students ages:
|
||||
|
||||
```js
|
||||
const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
|
||||
```
|
||||
|
||||
- Sort the array and find the min and 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)
|
||||
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](../04_Day_Conditionals/04_day_Conditionals.md) | [Day 6 >>](../06_Day_Loops/06_day_loops.md)
|
@ -0,0 +1,195 @@
|
||||
const countries = [
|
||||
'Afghanistan',
|
||||
'Albania',
|
||||
'Algeria',
|
||||
'Andorra',
|
||||
'Angola',
|
||||
'Antigua and Barbuda',
|
||||
'Argentina',
|
||||
'Armenia',
|
||||
'Australia',
|
||||
'Austria',
|
||||
'Azerbaijan',
|
||||
'Bahamas',
|
||||
'Bahrain',
|
||||
'Bangladesh',
|
||||
'Barbados',
|
||||
'Belarus',
|
||||
'Belgium',
|
||||
'Belize',
|
||||
'Benin',
|
||||
'Bhutan',
|
||||
'Bolivia',
|
||||
'Bosnia and Herzegovina',
|
||||
'Botswana',
|
||||
'Brazil',
|
||||
'Brunei',
|
||||
'Bulgaria',
|
||||
'Burkina Faso',
|
||||
'Burundi',
|
||||
'Cambodia',
|
||||
'Cameroon',
|
||||
'Canada',
|
||||
'Cape Verde',
|
||||
'Central African Republic',
|
||||
'Chad',
|
||||
'Chile',
|
||||
'China',
|
||||
'Colombi',
|
||||
'Comoros',
|
||||
'Congo (Brazzaville)',
|
||||
'Congo',
|
||||
'Costa Rica',
|
||||
"Cote d'Ivoire",
|
||||
'Croatia',
|
||||
'Cuba',
|
||||
'Cyprus',
|
||||
'Czech Republic',
|
||||
'Denmark',
|
||||
'Djibouti',
|
||||
'Dominica',
|
||||
'Dominican Republic',
|
||||
'East Timor (Timor Timur)',
|
||||
'Ecuador',
|
||||
'Egypt',
|
||||
'El Salvador',
|
||||
'Equatorial Guinea',
|
||||
'Eritrea',
|
||||
'Estonia',
|
||||
'Ethiopia',
|
||||
'Fiji',
|
||||
'Finland',
|
||||
'France',
|
||||
'Gabon',
|
||||
'Gambia, The',
|
||||
'Georgia',
|
||||
'Germany',
|
||||
'Ghana',
|
||||
'Greece',
|
||||
'Grenada',
|
||||
'Guatemala',
|
||||
'Guinea',
|
||||
'Guinea-Bissau',
|
||||
'Guyana',
|
||||
'Haiti',
|
||||
'Honduras',
|
||||
'Hungary',
|
||||
'Iceland',
|
||||
'India',
|
||||
'Indonesia',
|
||||
'Iran',
|
||||
'Iraq',
|
||||
'Ireland',
|
||||
'Israel',
|
||||
'Italy',
|
||||
'Jamaica',
|
||||
'Japan',
|
||||
'Jordan',
|
||||
'Kazakhstan',
|
||||
'Kenya',
|
||||
'Kiribati',
|
||||
'Korea, North',
|
||||
'Korea, South',
|
||||
'Kuwait',
|
||||
'Kyrgyzstan',
|
||||
'Laos',
|
||||
'Latvia',
|
||||
'Lebanon',
|
||||
'Lesotho',
|
||||
'Liberia',
|
||||
'Libya',
|
||||
'Liechtenstein',
|
||||
'Lithuania',
|
||||
'Luxembourg',
|
||||
'Macedonia',
|
||||
'Madagascar',
|
||||
'Malawi',
|
||||
'Malaysia',
|
||||
'Maldives',
|
||||
'Mali',
|
||||
'Malta',
|
||||
'Marshall Islands',
|
||||
'Mauritania',
|
||||
'Mauritius',
|
||||
'Mexico',
|
||||
'Micronesia',
|
||||
'Moldova',
|
||||
'Monaco',
|
||||
'Mongolia',
|
||||
'Morocco',
|
||||
'Mozambique',
|
||||
'Myanmar',
|
||||
'Namibia',
|
||||
'Nauru',
|
||||
'Nepal',
|
||||
'Netherlands',
|
||||
'New Zealand',
|
||||
'Nicaragua',
|
||||
'Niger',
|
||||
'Nigeria',
|
||||
'Norway',
|
||||
'Oman',
|
||||
'Pakistan',
|
||||
'Palau',
|
||||
'Panama',
|
||||
'Papua New Guinea',
|
||||
'Paraguay',
|
||||
'Peru',
|
||||
'Philippines',
|
||||
'Poland',
|
||||
'Portugal',
|
||||
'Qatar',
|
||||
'Romania',
|
||||
'Russia',
|
||||
'Rwanda',
|
||||
'Saint Kitts and Nevis',
|
||||
'Saint Lucia',
|
||||
'Saint Vincent',
|
||||
'Samoa',
|
||||
'San Marino',
|
||||
'Sao Tome and Principe',
|
||||
'Saudi Arabia',
|
||||
'Senegal',
|
||||
'Serbia and Montenegro',
|
||||
'Seychelles',
|
||||
'Sierra Leone',
|
||||
'Singapore',
|
||||
'Slovakia',
|
||||
'Slovenia',
|
||||
'Solomon Islands',
|
||||
'Somalia',
|
||||
'South Africa',
|
||||
'Spain',
|
||||
'Sri Lanka',
|
||||
'Sudan',
|
||||
'Suriname',
|
||||
'Swaziland',
|
||||
'Sweden',
|
||||
'Switzerland',
|
||||
'Syria',
|
||||
'Taiwan',
|
||||
'Tajikistan',
|
||||
'Tanzania',
|
||||
'Thailand',
|
||||
'Togo',
|
||||
'Tonga',
|
||||
'Trinidad and Tobago',
|
||||
'Tunisia',
|
||||
'Turkey',
|
||||
'Turkmenistan',
|
||||
'Tuvalu',
|
||||
'Uganda',
|
||||
'Ukraine',
|
||||
'United Arab Emirates',
|
||||
'United Kingdom',
|
||||
'United States',
|
||||
'Uruguay',
|
||||
'Uzbekistan',
|
||||
'Vanuatu',
|
||||
'Vatican City',
|
||||
'Venezuela',
|
||||
'Vietnam',
|
||||
'Yemen',
|
||||
'Zambia',
|
||||
'Zimbabwe'
|
||||
]
|
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript:05 Day </title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>30DaysOfJavaScript:05 Day</h1>
|
||||
<h2>Arrays</h2>
|
||||
|
||||
<script src="./data/countries.js"></script>
|
||||
<script src="./scripts/main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1,3 @@
|
||||
console.log(countries)
|
||||
alert('Open the browser console whenever you work on JavaScript')
|
||||
alert('Open the console and check if the countries has been loaded')
|
@ -0,0 +1,481 @@
|
||||
<div align="center">
|
||||
<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>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Author:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> January, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 5](../05_Day_Arrays/05_day_arrays.md) | [Day 7 >>](../07_Day_Functions/07_day_functions.md)
|
||||
|
||||

|
||||
|
||||
- [📔 Day 6](#-day-6)
|
||||
- [Loops](#loops)
|
||||
- [for Loop](#for-loop)
|
||||
- [while loop](#while-loop)
|
||||
- [do while loop](#do-while-loop)
|
||||
- [for of loop](#for-of-loop)
|
||||
- [break](#break)
|
||||
- [continue](#continue)
|
||||
- [💻 Exercises:Day 6](#-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. 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 loops. The following examples are the commonly used loops in JavaScript and other programming languages.
|
||||
|
||||
### for Loop
|
||||
|
||||
```js
|
||||
// For loop structure
|
||||
for(initialization, condition, increment/decrement){
|
||||
// code goes here
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
for(let i = 0; i <= 5; i++){
|
||||
console.log(i)
|
||||
}
|
||||
|
||||
// 0 1 2 3 4 5
|
||||
```
|
||||
|
||||
```js
|
||||
for(let i = 5; i >= 0; i--){
|
||||
console.log(i)
|
||||
}
|
||||
|
||||
// 5 4 3 2 1 0
|
||||
```
|
||||
|
||||
```js
|
||||
for(let i = 0; i <= 5; i++){
|
||||
console.log(`${i} * ${i} = ${i * i}`)
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
0 * 0 = 0
|
||||
1 * 1 = 1
|
||||
2 * 2 = 4
|
||||
3 * 3 = 9
|
||||
4 * 4 = 16
|
||||
5 * 5 = 25
|
||||
```
|
||||
|
||||
```js
|
||||
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']
|
||||
const newArr = []
|
||||
for(let i = 0; i < countries.length; i++){
|
||||
newArr.push(countries[i].toUpperCase())
|
||||
}
|
||||
|
||||
// ["FINLAND", "SWEDEN", "DENMARK", "NORWAY", "ICELAND"]
|
||||
```
|
||||
|
||||
Adding all elements in the array
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
let sum = 0
|
||||
for(let i = 0; i < numbers.length; i++){
|
||||
sum = sum + numbers[i] // can be shorten, sum += numbers[i]
|
||||
|
||||
}
|
||||
|
||||
console.log(sum) // 15
|
||||
```
|
||||
|
||||
Creating a new array based on the existing array
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
const newArr = []
|
||||
let sum = 0
|
||||
for(let i = 0; i < numbers.length; i++){
|
||||
newArr.push(i * i)
|
||||
|
||||
}
|
||||
|
||||
console.log(newArr) // [1, 4, 9, 16, 25]
|
||||
```
|
||||
|
||||
```js
|
||||
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
|
||||
const newArr = []
|
||||
for(let i = 0; i < countries.length; i++){
|
||||
newArr.push(countries[i].toUpperCase())
|
||||
}
|
||||
|
||||
console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
|
||||
```
|
||||
|
||||
### while loop
|
||||
|
||||
```js
|
||||
let i = 0
|
||||
while (i <= 5) {
|
||||
console.log(i)
|
||||
i++
|
||||
}
|
||||
|
||||
// 0 1 2 3 4 5
|
||||
```
|
||||
|
||||
### do while loop
|
||||
|
||||
```js
|
||||
let i = 0
|
||||
do {
|
||||
console.log(i)
|
||||
i++
|
||||
} while (i <= 5)
|
||||
|
||||
// 0 1 2 3 4 5
|
||||
```
|
||||
|
||||
### for of loop
|
||||
|
||||
We use for of loop for arrays. It is very hand way to iterate through an array if we are not interested in the index of each element in the array.
|
||||
|
||||
```js
|
||||
for (const element of arr) {
|
||||
// code goes here
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
for (const num of numbers) {
|
||||
console.log(num)
|
||||
}
|
||||
|
||||
// 1 2 3 4 5
|
||||
|
||||
for (const num of numbers) {
|
||||
console.log(num * num)
|
||||
}
|
||||
|
||||
// 1 4 9 16 25
|
||||
|
||||
// adding all the numbers in the array
|
||||
let sum = 0
|
||||
for (const num of numbers) {
|
||||
sum += sum + num // can be also shorten like this, sum += num
|
||||
}
|
||||
console.log(sum) // 15
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
]
|
||||
|
||||
for (const tech of webTechs) {
|
||||
console.log(tech.toUpperCase())
|
||||
}
|
||||
|
||||
// HTML CSS JAVASCRIPT REACT NODE MONGODB
|
||||
|
||||
for (const tech of webTechs) {
|
||||
console.log(tech[0]) // get only the first letter of each element, H C J R N M
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
```js
|
||||
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
|
||||
const newArr = []
|
||||
for(const country of countries){
|
||||
newArr.push(country.toUpperCase())
|
||||
}
|
||||
|
||||
console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
|
||||
```
|
||||
|
||||
### break
|
||||
|
||||
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
|
||||
|
||||
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',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya'
|
||||
]
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
]
|
||||
|
||||
const mernStack = ['MongoDB', 'Express', 'React', 'Node']
|
||||
```
|
||||
|
||||
1. Iterate 0 to 10 using for loop, do the same using while and do while loop
|
||||
2. Iterate 10 to 0 using for loop, do the same using while and do while loop
|
||||
3. Iterate 0 to n using for loop
|
||||
4. Write a loop that makes the following pattern using console.log():
|
||||
|
||||
```js
|
||||
#
|
||||
##
|
||||
###
|
||||
####
|
||||
#####
|
||||
######
|
||||
#######
|
||||
```
|
||||
|
||||
5. Use loop to print the following pattern:
|
||||
|
||||
```sh
|
||||
0 x 0 = 0
|
||||
1 x 1 = 1
|
||||
2 x 2 = 4
|
||||
3 x 3 = 9
|
||||
4 x 4 = 16
|
||||
5 x 5 = 25
|
||||
6 x 6 = 36
|
||||
7 x 7 = 49
|
||||
8 x 8 = 64
|
||||
9 x 9 = 81
|
||||
10 x 10 = 100
|
||||
```
|
||||
|
||||
6. Using loop print the following pattern
|
||||
|
||||
```sh
|
||||
i i^2 i^3
|
||||
0 0 0
|
||||
1 1 1
|
||||
2 4 8
|
||||
3 9 27
|
||||
4 16 64
|
||||
5 25 125
|
||||
6 36 216
|
||||
7 49 343
|
||||
8 64 512
|
||||
9 81 729
|
||||
10 100 1000
|
||||
```
|
||||
|
||||
7. Use for loop to iterate from 0 to 100 and print only even numbers
|
||||
8. Use for loop to iterate from 0 to 100 and print only odd numbers
|
||||
9. Use for loop to iterate from 0 to 100 and print only prime numbers
|
||||
10. Use for loop to iterate from 0 to 100 and print the sum of all numbers.
|
||||
|
||||
```sh
|
||||
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 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
|
||||
|
||||
```sh
|
||||
[2550, 2500]
|
||||
```
|
||||
|
||||
13. Develop a small script which generate array of 5 random numbers
|
||||
14. Develop a small script which generate array of 5 random numbers and the numbers must be unique
|
||||
15. Develop a small script which generate a six characters random id:
|
||||
|
||||
```sh
|
||||
5j2khz
|
||||
```
|
||||
|
||||
### Exercises: Level 2
|
||||
|
||||
1. Develop a small script which generate any number of characters random id:
|
||||
|
||||
```sh
|
||||
fe3jo1gl124g
|
||||
```
|
||||
|
||||
```sh
|
||||
xkqci4utda1lmbelpkm03rba
|
||||
```
|
||||
|
||||
1. Write a script which generates a random hexadecimal number.
|
||||
|
||||
```sh
|
||||
'#ee33df'
|
||||
```
|
||||
|
||||
1. Write a script which generates a random rgb color number.
|
||||
|
||||
```sh
|
||||
rgb(240,180,80)
|
||||
```
|
||||
|
||||
1. Using the above countries array, create the following new array.
|
||||
|
||||
```sh
|
||||
["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"]
|
||||
```
|
||||
|
||||
1. Using the above countries array, create an array for countries length'.
|
||||
|
||||
```sh
|
||||
[7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5]
|
||||
```
|
||||
|
||||
1. Use the countries array to create the following array of arrays:
|
||||
|
||||
```sh
|
||||
[
|
||||
['Albania', 'ALB', 7],
|
||||
['Bolivia', 'BOL', 7],
|
||||
['Canada', 'CAN', 6],
|
||||
['Denmark', 'DEN', 7],
|
||||
['Ethiopia', 'ETH', 8],
|
||||
['Finland', 'FIN', 7],
|
||||
['Germany', 'GER', 7],
|
||||
['Hungary', 'HUN', 7],
|
||||
['Ireland', 'IRE', 7],
|
||||
['Japan', 'JAP', 5],
|
||||
['Kenya', 'KEN', 5]
|
||||
]
|
||||
```
|
||||
|
||||
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']
|
||||
```
|
||||
|
||||
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']
|
||||
```
|
||||
|
||||
4. Using the above countries array, find the country containing the biggest number of characters.
|
||||
|
||||
```sh
|
||||
Ethiopia
|
||||
```
|
||||
|
||||
5. Using the above countries array, find the country containing only 5 characters.
|
||||
|
||||
```sh
|
||||
['Japan', 'Kenya']
|
||||
```
|
||||
|
||||
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]]
|
||||
```
|
||||
|
||||
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 = [
|
||||
['HTML', 'CSS', 'JS', 'React'],
|
||||
['Node', 'Express', 'MongoDB']
|
||||
]
|
||||
````
|
||||
|
||||
```sh
|
||||
HTML
|
||||
CSS
|
||||
JS
|
||||
REACT
|
||||
NODE
|
||||
EXPRESS
|
||||
MONGODB
|
||||
```
|
||||
|
||||
### 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](../05_Day_Arrays/05_day_arrays.md) | [Day 7 >>](../07_Day_Functions/07_day_functions.md)
|
@ -0,0 +1,195 @@
|
||||
const countries = [
|
||||
'Afghanistan',
|
||||
'Albania',
|
||||
'Algeria',
|
||||
'Andorra',
|
||||
'Angola',
|
||||
'Antigua and Barbuda',
|
||||
'Argentina',
|
||||
'Armenia',
|
||||
'Australia',
|
||||
'Austria',
|
||||
'Azerbaijan',
|
||||
'Bahamas',
|
||||
'Bahrain',
|
||||
'Bangladesh',
|
||||
'Barbados',
|
||||
'Belarus',
|
||||
'Belgium',
|
||||
'Belize',
|
||||
'Benin',
|
||||
'Bhutan',
|
||||
'Bolivia',
|
||||
'Bosnia and Herzegovina',
|
||||
'Botswana',
|
||||
'Brazil',
|
||||
'Brunei',
|
||||
'Bulgaria',
|
||||
'Burkina Faso',
|
||||
'Burundi',
|
||||
'Cambodia',
|
||||
'Cameroon',
|
||||
'Canada',
|
||||
'Cape Verde',
|
||||
'Central African Republic',
|
||||
'Chad',
|
||||
'Chile',
|
||||
'China',
|
||||
'Colombi',
|
||||
'Comoros',
|
||||
'Congo (Brazzaville)',
|
||||
'Congo',
|
||||
'Costa Rica',
|
||||
"Cote d'Ivoire",
|
||||
'Croatia',
|
||||
'Cuba',
|
||||
'Cyprus',
|
||||
'Czech Republic',
|
||||
'Denmark',
|
||||
'Djibouti',
|
||||
'Dominica',
|
||||
'Dominican Republic',
|
||||
'East Timor (Timor Timur)',
|
||||
'Ecuador',
|
||||
'Egypt',
|
||||
'El Salvador',
|
||||
'Equatorial Guinea',
|
||||
'Eritrea',
|
||||
'Estonia',
|
||||
'Ethiopia',
|
||||
'Fiji',
|
||||
'Finland',
|
||||
'France',
|
||||
'Gabon',
|
||||
'Gambia, The',
|
||||
'Georgia',
|
||||
'Germany',
|
||||
'Ghana',
|
||||
'Greece',
|
||||
'Grenada',
|
||||
'Guatemala',
|
||||
'Guinea',
|
||||
'Guinea-Bissau',
|
||||
'Guyana',
|
||||
'Haiti',
|
||||
'Honduras',
|
||||
'Hungary',
|
||||
'Iceland',
|
||||
'India',
|
||||
'Indonesia',
|
||||
'Iran',
|
||||
'Iraq',
|
||||
'Ireland',
|
||||
'Israel',
|
||||
'Italy',
|
||||
'Jamaica',
|
||||
'Japan',
|
||||
'Jordan',
|
||||
'Kazakhstan',
|
||||
'Kenya',
|
||||
'Kiribati',
|
||||
'Korea, North',
|
||||
'Korea, South',
|
||||
'Kuwait',
|
||||
'Kyrgyzstan',
|
||||
'Laos',
|
||||
'Latvia',
|
||||
'Lebanon',
|
||||
'Lesotho',
|
||||
'Liberia',
|
||||
'Libya',
|
||||
'Liechtenstein',
|
||||
'Lithuania',
|
||||
'Luxembourg',
|
||||
'Macedonia',
|
||||
'Madagascar',
|
||||
'Malawi',
|
||||
'Malaysia',
|
||||
'Maldives',
|
||||
'Mali',
|
||||
'Malta',
|
||||
'Marshall Islands',
|
||||
'Mauritania',
|
||||
'Mauritius',
|
||||
'Mexico',
|
||||
'Micronesia',
|
||||
'Moldova',
|
||||
'Monaco',
|
||||
'Mongolia',
|
||||
'Morocco',
|
||||
'Mozambique',
|
||||
'Myanmar',
|
||||
'Namibia',
|
||||
'Nauru',
|
||||
'Nepal',
|
||||
'Netherlands',
|
||||
'New Zealand',
|
||||
'Nicaragua',
|
||||
'Niger',
|
||||
'Nigeria',
|
||||
'Norway',
|
||||
'Oman',
|
||||
'Pakistan',
|
||||
'Palau',
|
||||
'Panama',
|
||||
'Papua New Guinea',
|
||||
'Paraguay',
|
||||
'Peru',
|
||||
'Philippines',
|
||||
'Poland',
|
||||
'Portugal',
|
||||
'Qatar',
|
||||
'Romania',
|
||||
'Russia',
|
||||
'Rwanda',
|
||||
'Saint Kitts and Nevis',
|
||||
'Saint Lucia',
|
||||
'Saint Vincent',
|
||||
'Samoa',
|
||||
'San Marino',
|
||||
'Sao Tome and Principe',
|
||||
'Saudi Arabia',
|
||||
'Senegal',
|
||||
'Serbia and Montenegro',
|
||||
'Seychelles',
|
||||
'Sierra Leone',
|
||||
'Singapore',
|
||||
'Slovakia',
|
||||
'Slovenia',
|
||||
'Solomon Islands',
|
||||
'Somalia',
|
||||
'South Africa',
|
||||
'Spain',
|
||||
'Sri Lanka',
|
||||
'Sudan',
|
||||
'Suriname',
|
||||
'Swaziland',
|
||||
'Sweden',
|
||||
'Switzerland',
|
||||
'Syria',
|
||||
'Taiwan',
|
||||
'Tajikistan',
|
||||
'Tanzania',
|
||||
'Thailand',
|
||||
'Togo',
|
||||
'Tonga',
|
||||
'Trinidad and Tobago',
|
||||
'Tunisia',
|
||||
'Turkey',
|
||||
'Turkmenistan',
|
||||
'Tuvalu',
|
||||
'Uganda',
|
||||
'Ukraine',
|
||||
'United Arab Emirates',
|
||||
'United Kingdom',
|
||||
'United States',
|
||||
'Uruguay',
|
||||
'Uzbekistan',
|
||||
'Vanuatu',
|
||||
'Vatican City',
|
||||
'Venezuela',
|
||||
'Vietnam',
|
||||
'Yemen',
|
||||
'Zambia',
|
||||
'Zimbabwe'
|
||||
]
|
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript:06 Day </title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>30DaysOfJavaScript:06 Day</h1>
|
||||
<h2>Loops</h2>
|
||||
|
||||
<script src="./data/countries.js"></script>
|
||||
<script src="./scripts/main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1,2 @@
|
||||
console.log(countries)
|
||||
alert('Open the console and check if the countries has been loaded')
|
@ -0,0 +1,195 @@
|
||||
const countries = [
|
||||
'Afghanistan',
|
||||
'Albania',
|
||||
'Algeria',
|
||||
'Andorra',
|
||||
'Angola',
|
||||
'Antigua and Barbuda',
|
||||
'Argentina',
|
||||
'Armenia',
|
||||
'Australia',
|
||||
'Austria',
|
||||
'Azerbaijan',
|
||||
'Bahamas',
|
||||
'Bahrain',
|
||||
'Bangladesh',
|
||||
'Barbados',
|
||||
'Belarus',
|
||||
'Belgium',
|
||||
'Belize',
|
||||
'Benin',
|
||||
'Bhutan',
|
||||
'Bolivia',
|
||||
'Bosnia and Herzegovina',
|
||||
'Botswana',
|
||||
'Brazil',
|
||||
'Brunei',
|
||||
'Bulgaria',
|
||||
'Burkina Faso',
|
||||
'Burundi',
|
||||
'Cambodia',
|
||||
'Cameroon',
|
||||
'Canada',
|
||||
'Cape Verde',
|
||||
'Central African Republic',
|
||||
'Chad',
|
||||
'Chile',
|
||||
'China',
|
||||
'Colombi',
|
||||
'Comoros',
|
||||
'Congo (Brazzaville)',
|
||||
'Congo',
|
||||
'Costa Rica',
|
||||
"Cote d'Ivoire",
|
||||
'Croatia',
|
||||
'Cuba',
|
||||
'Cyprus',
|
||||
'Czech Republic',
|
||||
'Denmark',
|
||||
'Djibouti',
|
||||
'Dominica',
|
||||
'Dominican Republic',
|
||||
'East Timor (Timor Timur)',
|
||||
'Ecuador',
|
||||
'Egypt',
|
||||
'El Salvador',
|
||||
'Equatorial Guinea',
|
||||
'Eritrea',
|
||||
'Estonia',
|
||||
'Ethiopia',
|
||||
'Fiji',
|
||||
'Finland',
|
||||
'France',
|
||||
'Gabon',
|
||||
'Gambia, The',
|
||||
'Georgia',
|
||||
'Germany',
|
||||
'Ghana',
|
||||
'Greece',
|
||||
'Grenada',
|
||||
'Guatemala',
|
||||
'Guinea',
|
||||
'Guinea-Bissau',
|
||||
'Guyana',
|
||||
'Haiti',
|
||||
'Honduras',
|
||||
'Hungary',
|
||||
'Iceland',
|
||||
'India',
|
||||
'Indonesia',
|
||||
'Iran',
|
||||
'Iraq',
|
||||
'Ireland',
|
||||
'Israel',
|
||||
'Italy',
|
||||
'Jamaica',
|
||||
'Japan',
|
||||
'Jordan',
|
||||
'Kazakhstan',
|
||||
'Kenya',
|
||||
'Kiribati',
|
||||
'Korea, North',
|
||||
'Korea, South',
|
||||
'Kuwait',
|
||||
'Kyrgyzstan',
|
||||
'Laos',
|
||||
'Latvia',
|
||||
'Lebanon',
|
||||
'Lesotho',
|
||||
'Liberia',
|
||||
'Libya',
|
||||
'Liechtenstein',
|
||||
'Lithuania',
|
||||
'Luxembourg',
|
||||
'Macedonia',
|
||||
'Madagascar',
|
||||
'Malawi',
|
||||
'Malaysia',
|
||||
'Maldives',
|
||||
'Mali',
|
||||
'Malta',
|
||||
'Marshall Islands',
|
||||
'Mauritania',
|
||||
'Mauritius',
|
||||
'Mexico',
|
||||
'Micronesia',
|
||||
'Moldova',
|
||||
'Monaco',
|
||||
'Mongolia',
|
||||
'Morocco',
|
||||
'Mozambique',
|
||||
'Myanmar',
|
||||
'Namibia',
|
||||
'Nauru',
|
||||
'Nepal',
|
||||
'Netherlands',
|
||||
'New Zealand',
|
||||
'Nicaragua',
|
||||
'Niger',
|
||||
'Nigeria',
|
||||
'Norway',
|
||||
'Oman',
|
||||
'Pakistan',
|
||||
'Palau',
|
||||
'Panama',
|
||||
'Papua New Guinea',
|
||||
'Paraguay',
|
||||
'Peru',
|
||||
'Philippines',
|
||||
'Poland',
|
||||
'Portugal',
|
||||
'Qatar',
|
||||
'Romania',
|
||||
'Russia',
|
||||
'Rwanda',
|
||||
'Saint Kitts and Nevis',
|
||||
'Saint Lucia',
|
||||
'Saint Vincent',
|
||||
'Samoa',
|
||||
'San Marino',
|
||||
'Sao Tome and Principe',
|
||||
'Saudi Arabia',
|
||||
'Senegal',
|
||||
'Serbia and Montenegro',
|
||||
'Seychelles',
|
||||
'Sierra Leone',
|
||||
'Singapore',
|
||||
'Slovakia',
|
||||
'Slovenia',
|
||||
'Solomon Islands',
|
||||
'Somalia',
|
||||
'South Africa',
|
||||
'Spain',
|
||||
'Sri Lanka',
|
||||
'Sudan',
|
||||
'Suriname',
|
||||
'Swaziland',
|
||||
'Sweden',
|
||||
'Switzerland',
|
||||
'Syria',
|
||||
'Taiwan',
|
||||
'Tajikistan',
|
||||
'Tanzania',
|
||||
'Thailand',
|
||||
'Togo',
|
||||
'Tonga',
|
||||
'Trinidad and Tobago',
|
||||
'Tunisia',
|
||||
'Turkey',
|
||||
'Turkmenistan',
|
||||
'Tuvalu',
|
||||
'Uganda',
|
||||
'Ukraine',
|
||||
'United Arab Emirates',
|
||||
'United Kingdom',
|
||||
'United States',
|
||||
'Uruguay',
|
||||
'Uzbekistan',
|
||||
'Vanuatu',
|
||||
'Vatican City',
|
||||
'Venezuela',
|
||||
'Vietnam',
|
||||
'Yemen',
|
||||
'Zambia',
|
||||
'Zimbabwe'
|
||||
]
|
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript:07 Day </title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>30DaysOfJavaScript:07 Day</h1>
|
||||
<h2>Functions</h2>
|
||||
|
||||
<script src="./data/countries.js"></script>
|
||||
<script src="./scripts/main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1,2 @@
|
||||
console.log(countries)
|
||||
alert('Open the console and check if the countries has been loaded')
|
@ -0,0 +1,589 @@
|
||||
<div align="center">
|
||||
<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>
|
||||
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
|
||||
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
|
||||
</a>
|
||||
|
||||
<sub>Author:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> January, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 7](../07_Day_Functions/07_day_functions.md) | [Day 9 >>](../09_Day_Higher_order_functions/09_day_higher_order_functions.md)
|
||||
|
||||

|
||||
|
||||
- [📔 Day 8](#-day-8)
|
||||
- [Scope](#scope)
|
||||
- [Window Scope](#window-scope)
|
||||
- [Global scope](#global-scope)
|
||||
- [Local scope](#local-scope)
|
||||
- [📔 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)
|
||||
- [Creating object methods](#creating-object-methods)
|
||||
- [Setting new key for an object](#setting-new-key-for-an-object)
|
||||
- [Object Methods](#object-methods)
|
||||
- [Getting object keys using Object.keys()](#getting-object-keys-using-objectkeys)
|
||||
- [Getting object values using Object.values()](#getting-object-values-using-objectvalues)
|
||||
- [Getting object keys and values using Object.entries()](#getting-object-keys-and-values-using-objectentries)
|
||||
- [Checking properties using hasOwnProperty()](#checking-properties-using-hasownproperty)
|
||||
- [💻 Exercises](#-exercises)
|
||||
- [Exercises: Level 1](#exercises-level-1)
|
||||
- [Exercises: Level 2](#exercises-level-2)
|
||||
- [Exercises: Level 3](#exercises-level-3)
|
||||
|
||||
# 📔 Day 8
|
||||
|
||||
## Scope
|
||||
|
||||
Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word _var_, _let_ and _const_. A variable can declared at different scope. In this section we will see the scope, scope of variables when we use var or let.
|
||||
Variables scopes can be:
|
||||
|
||||
- Window
|
||||
- Global
|
||||
- Local
|
||||
|
||||
Variable can be declared globally or locally or window scope. We will see both global and local scope.
|
||||
Anything declared without let, var or const is scoped at window level.
|
||||
|
||||
Let us image we have a scope.js file.
|
||||
|
||||
### Window Scope
|
||||
|
||||
Without using console.log() open your browser and check, you will see the value of a and b if you write a or b on the browser. That means a and b are already available in the window.
|
||||
|
||||
```js
|
||||
//scope.js
|
||||
a = 'JavaScript' // is a window scope this found anywhere
|
||||
b = 10 // this is a window scope variable
|
||||
function letsLearnScope() {
|
||||
console.log(a, b)
|
||||
if (true) {
|
||||
console.log(a, b)
|
||||
}
|
||||
}
|
||||
console.log(a, b) // accessible
|
||||
```
|
||||
|
||||
### Global scope
|
||||
|
||||
A globally declared variable can be 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
|
||||
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
|
||||
let b = 10 // is a global scope it will be found anywhere in this file
|
||||
function letsLearnScope() {
|
||||
console.log(a, b) // JavaScript 10, accessible
|
||||
if (true) {
|
||||
let a = 'Python'
|
||||
let b = 100
|
||||
console.log(a, b) // Python 100
|
||||
}
|
||||
console.log(a, b)
|
||||
}
|
||||
letsLearnScope()
|
||||
console.log(a, b) // JavaScript 10, accessible
|
||||
```
|
||||
|
||||
### Local scope
|
||||
|
||||
A variable declared as local can be accessed only in certain block code.
|
||||
|
||||
```js
|
||||
//scope.js
|
||||
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
|
||||
let b = 10 // is a global scope it will be found anywhere in this file
|
||||
function letsLearnScope() {
|
||||
console.log(a, b) // JavaScript 10, accessible
|
||||
let c = 30
|
||||
if (true) {
|
||||
// we can access from the function and outside the function but
|
||||
// variables declared inside the if will not be accessed outside the if block
|
||||
let a = 'Python'
|
||||
let b = 20
|
||||
let d = 40
|
||||
console.log(a, b, c) // Python 20 30
|
||||
}
|
||||
// we can not access c because c's scope is only the if block
|
||||
console.log(a, b) // JavaScript 10
|
||||
}
|
||||
letsLearnScope()
|
||||
console.log(a, b) // JavaScript 10, accessible
|
||||
```
|
||||
|
||||
Now, you have an understanding of scope. A variable declared with *var* only scoped to function but variable declared with *let* or *const* is block scope(function block, if block, loop etc). Block in JavaScript is a code in between two curly brackets ({}).
|
||||
|
||||
```js
|
||||
//scope.js
|
||||
function letsLearnScope() {
|
||||
var gravity = 9.81
|
||||
console.log(gravity)
|
||||
|
||||
}
|
||||
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
|
||||
|
||||
if (true){
|
||||
var gravity = 9.81
|
||||
console.log(gravity) // 9.81
|
||||
}
|
||||
console.log(gravity) // 9.81
|
||||
|
||||
for(var i = 0; i < 3; i++){
|
||||
console.log(i) // 1, 2, 3
|
||||
}
|
||||
console.log(i)
|
||||
|
||||
```
|
||||
|
||||
In ES6 and above there is *let* and *const*, so you will 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
|
||||
function letsLearnScope() {
|
||||
// you can use let or const, but gravity is constant I prefer to use const
|
||||
const gravity = 9.81
|
||||
console.log(gravity)
|
||||
|
||||
}
|
||||
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
|
||||
|
||||
if (true){
|
||||
const gravity = 9.81
|
||||
console.log(gravity) // 9.81
|
||||
}
|
||||
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
|
||||
|
||||
for(let i = 0; i < 3; i++){
|
||||
console.log(i) // 1, 2, 3
|
||||
}
|
||||
// console.log(i), Uncaught ReferenceError: gravity is not defined
|
||||
|
||||
```
|
||||
|
||||
The scope *let* and *const* is the same. The difference is only reassigning. We can not change or reassign the value of const variable. I would strongly suggest you to use *let* and *const*, by using *let* and *const* you will writ clean code and avoid hard to debug mistakes. As a rule of thumb, you can use *let* for any value which change, *const* for any constant value, 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 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
|
||||
|
||||
An empty object
|
||||
|
||||
```js
|
||||
const person = {}
|
||||
```
|
||||
|
||||
### Creating an objecting with values
|
||||
|
||||
Now, the person object has firstName, lastName, age, location, skills and isMarried properties. The value of properties or keys could be a string, number, boolean, an object, null, undefined or a function.
|
||||
|
||||
Let us see some examples of object. Each key has a value in the object.
|
||||
|
||||
```js
|
||||
const rectangle = {
|
||||
length: 20,
|
||||
width: 20
|
||||
}
|
||||
console.log(rectangle) // {length: 20, width: 20}
|
||||
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js'
|
||||
],
|
||||
isMarried: true
|
||||
}
|
||||
console.log(person)
|
||||
```
|
||||
|
||||
### Getting values from an object
|
||||
|
||||
We can access values of object using two methods:
|
||||
|
||||
- using . followed by key name if the key-name is a one word
|
||||
- using square bracket and a quote
|
||||
|
||||
```js
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js'
|
||||
],
|
||||
getFullName: function() {
|
||||
return `${this.firstName}${this.lastName}`
|
||||
},
|
||||
'phone number': '+3584545454545'
|
||||
}
|
||||
|
||||
// accessing values using .
|
||||
console.log(person.firstName)
|
||||
console.log(person.lastName)
|
||||
console.log(person.age)
|
||||
console.log(person.location)
|
||||
|
||||
// value can be accessed using square bracket and key name
|
||||
console.log(person['firstName'])
|
||||
console.log(person['lastName'])
|
||||
console.log(person['age'])
|
||||
console.log(person['age'])
|
||||
console.log(person['location'])
|
||||
|
||||
// for instance to access the phone number we only use the square bracket method
|
||||
console.log(person['phone number'])
|
||||
```
|
||||
|
||||
### Creating object methods
|
||||
|
||||
Now, the person object has getFullName properties. The getFullName is function inside the person object and we call it an object method. The _this_ key word refers to the object itself. We can use the word _this_ to access the values of different properties of the object. We can not use an arrow function as object method because the word this refers to the window inside an arrow function instead of the object itself. Example of object:
|
||||
|
||||
```js
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js'
|
||||
],
|
||||
getFullName: function() {
|
||||
return `${this.firstName} ${this.lastName}`
|
||||
}
|
||||
}
|
||||
|
||||
console.log(person.getFullName())
|
||||
// Asabeneh Yetayeh
|
||||
```
|
||||
|
||||
### Setting new key for an object
|
||||
|
||||
An object is a mutable data structure and we can modify the content of an object after it gets created.
|
||||
|
||||
Setting a new keys in an object
|
||||
|
||||
```js
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js'
|
||||
],
|
||||
getFullName: function() {
|
||||
return `${this.firstName} ${this.lastName}`
|
||||
}
|
||||
}
|
||||
person.nationality = 'Ethiopian'
|
||||
person.country = 'Finland'
|
||||
person.title = 'teacher'
|
||||
person.skills.push('Meteor')
|
||||
person.skills.push('SasS')
|
||||
person.isMarried = true
|
||||
|
||||
person.getPersonInfo = function() {
|
||||
let skillsWithoutLastSkill = this.skills
|
||||
.splice(0, this.skills.length - 1)
|
||||
.join(', ')
|
||||
let lastSkill = this.skills.splice(this.skills.length - 1)[0]
|
||||
|
||||
let skills = `${skillsWithoutLastSkill}, and ${lastSkill}`
|
||||
let fullName = this.getFullName()
|
||||
let statement = `${fullName} is a ${this.title}.\nHe lives in ${this.country}.\nHe teaches ${skills}.`
|
||||
return statement
|
||||
}
|
||||
console.log(person)
|
||||
console.log(person.getPersonInfo())
|
||||
```
|
||||
|
||||
```sh
|
||||
Asabeneh Yetayeh is a teacher.
|
||||
He lives in Finland.
|
||||
He teaches HTML, CSS, JavaScript, React, Node, MongoDB, Python, D3.js, Meteor, and SasS.
|
||||
```
|
||||
|
||||
### Object Methods
|
||||
|
||||
There are different methods to manipulate an object. Let us see some of the available methods.
|
||||
|
||||
_Object.assign_: To copy an object without modifying the original object
|
||||
|
||||
```js
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city:'Helsinki',
|
||||
skills: ['HTML', 'CSS', 'JS'],
|
||||
title: 'teacher',
|
||||
address: {
|
||||
street: 'Heitamienkatu 16',
|
||||
pobox: 2002,
|
||||
city: 'Helsinki'
|
||||
},
|
||||
getPersonInfo: function() {
|
||||
return `I am ${this.firstName} and I live in ${this.city}, ${this.country}. I am ${this.age}.`
|
||||
}
|
||||
}
|
||||
|
||||
//Object methods: Object.assign, Object.keys, Object.values, Object.entries
|
||||
//hasOwnProperty
|
||||
|
||||
const copyPerson = Object.assign({}, person)
|
||||
console.log(copyPerson)
|
||||
```
|
||||
|
||||
#### Getting object keys using Object.keys()
|
||||
|
||||
_Object.keys_: To get the keys or properties of an object as an array
|
||||
|
||||
```js
|
||||
const keys = Object.keys(copyPerson)
|
||||
console.log(keys) //['name', 'age', 'country', 'skills', 'address', 'getPersonInfo']
|
||||
const address = Object.keys(copyPerson.address)
|
||||
console.log(address) //['street', 'pobox', 'city']
|
||||
```
|
||||
|
||||
#### Getting object values using Object.values()
|
||||
|
||||
_Object.values_:To get values of an object as an array
|
||||
|
||||
```js
|
||||
const values = Object.values(copyPerson)
|
||||
console.log(values)
|
||||
```
|
||||
|
||||
#### Getting object keys and values using Object.entries()
|
||||
|
||||
_Object.entries_:To get the keys and values in an array
|
||||
|
||||
```js
|
||||
const entries = Object.entries(copyPerson)
|
||||
console.log(entries)
|
||||
```
|
||||
|
||||
#### Checking properties using hasOwnProperty()
|
||||
|
||||
_hasOwnProperty_: To check if a specific key or property exist in an object
|
||||
|
||||
```js
|
||||
console.log(copyPerson.hasOwnProperty('name'))
|
||||
console.log(copyPerson.hasOwnProperty('score'))
|
||||
```
|
||||
|
||||
🌕 You are astonishing. Now, you are super charged with the power of objects. You have just completed day 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
|
||||
|
||||
### 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
|
||||
const users = {
|
||||
Alex: {
|
||||
email: 'alex@alex.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 30
|
||||
},
|
||||
Asab: {
|
||||
email: 'asab@asab.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
|
||||
age: 25,
|
||||
isLoggedIn: false,
|
||||
points: 50
|
||||
},
|
||||
Brook: {
|
||||
email: 'daniel@daniel.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
|
||||
age: 30,
|
||||
isLoggedIn: true,
|
||||
points: 50
|
||||
},
|
||||
Daniel: {
|
||||
email: 'daniel@alex.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
},
|
||||
John: {
|
||||
email: 'john@john.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
|
||||
age: 20,
|
||||
isLoggedIn: true,
|
||||
points: 50
|
||||
},
|
||||
Thomas: {
|
||||
email: 'thomas@thomas.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
},
|
||||
Paul: {
|
||||
email: 'paul@paul.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
}
|
||||
}```
|
||||
|
||||
1. Find people who are MERN stack developer from the users object
|
||||
1. Set your name in the users object without modifying the original users object
|
||||
1. Get all keys or properties of users object
|
||||
1. Get all the values of users object
|
||||
1. Use the countries object to print a country name, capital, populations and languages.
|
||||
|
||||
### 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](../07_Day_Functions/07_day_functions.md) | [Day 9 >>](../09_Day_Higher_order_functions/09_day_higher_order_functions.md)
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript:08 Day </title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>30DaysOfJavaScript:08 Day</h1>
|
||||
<h2>Objects</h2>
|
||||
|
||||
<script src="./data/countries_data.js"></script>
|
||||
<script src="./scripts/main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1,2 @@
|
||||
console.log(countries)
|
||||
alert('Open the console and check if the countries has been loaded')
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,17 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>30DaysOfJavaScript:09 Day </title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>30DaysOfJavaScript:09 Day</h1>
|
||||
<h2>Functional Programming</h2>
|
||||
|
||||
<script src="./data/countries_data.js"></script>
|
||||
<script src="./scripts/main.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
@ -0,0 +1,2 @@
|
||||
console.log(countries)
|
||||
alert('Open the console and check if the countries has been loaded')
|
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')
|
File diff suppressed because it is too large
Load Diff
@ -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')
|
File diff suppressed because it is too large
Load Diff
@ -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)
|
||||
|
||||

|
||||
|
||||
- [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)
|
File diff suppressed because it is too large
Load Diff
@ -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)
|
||||
|
||||

|
||||
|
||||
- [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 it 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')
|
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)
|
||||
|
||||

|
||||
|
||||
- [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>
|
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')
|
@ -0,0 +1,104 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Closures</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 18](../18_Day_Promises/18_day_promise.md) | [Day 20 >>](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md)
|
||||
|
||||

|
||||
- [Day 19](#day-19)
|
||||
- [Closure](#closure)
|
||||
- [Exercises](#exercises)
|
||||
- [Exercises: Level 1](#exercises-level-1)
|
||||
- [Exercises: Level 2](#exercises-level-2)
|
||||
- [Exercises: Level 3](#exercises-level-3)
|
||||
|
||||
# Day 19
|
||||
|
||||
## Closure
|
||||
|
||||
JavaScript allows writing function inside an outer function. We can write as many inner functions as we want. If inner function access the variables of outer function then it is called closure.
|
||||
|
||||
```js
|
||||
function outerFunction() {
|
||||
let count = 0;
|
||||
function innerFunction() {
|
||||
count++
|
||||
return count
|
||||
}
|
||||
|
||||
return innerFunction
|
||||
}
|
||||
const innerFunc = outerFunction()
|
||||
|
||||
console.log(innerFunc())
|
||||
console.log(innerFunc())
|
||||
console.log(innerFunc())
|
||||
```
|
||||
|
||||
```sh
|
||||
1
|
||||
2
|
||||
3
|
||||
```
|
||||
|
||||
Let us more example of inner functions
|
||||
|
||||
```js
|
||||
function outerFunction() {
|
||||
let count = 0;
|
||||
function plusOne() {
|
||||
count++
|
||||
return count
|
||||
}
|
||||
function minusOne() {
|
||||
count--
|
||||
return count
|
||||
}
|
||||
|
||||
return {
|
||||
plusOne:plusOne(),
|
||||
minusOne:minusOne()
|
||||
}
|
||||
}
|
||||
const innerFuncs = outerFunction()
|
||||
|
||||
console.log(innerFuncs.plusOne)
|
||||
console.log(innerFuncs.minusOne)
|
||||
```
|
||||
|
||||
```sh
|
||||
1
|
||||
1
|
||||
```
|
||||
|
||||
🌕 You are making progress. Maintain your momentum, keep the good work. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## Exercises
|
||||
|
||||
### Exercises: Level 1
|
||||
|
||||
1. Create a closure which has one inner function
|
||||
|
||||
### Exercises: Level 2
|
||||
|
||||
1. Create a closure which has three inner functions
|
||||
|
||||
### Exercises: Level 3
|
||||
|
||||
1. Create a personAccount out function. It has firstname, lastname, incomes, expenses inner variables. It has totalIncome, totalExpense, accountInfo,addIncome, addExpense and accountBalance inner functions. Incomes is a set of incomes and its description and expenses is also a set of expenses and its description.
|
||||
|
||||
🎉 CONGRATULATIONS ! 🎉
|
||||
|
||||
[<< Day 18](../18_Day_Promises/18_day_promise.md) | [Day 20 >>](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md)
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue