Merge branch 'master' into master

pull/198/head
kalifun 4 years ago committed by GitHub
commit 4317ba3fce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript</title> <title>30DaysOfJavaScript</title>
@ -11,7 +11,7 @@
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button> <button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button>
<script src="./helloworld.js"></script> <script src="./helloworld.js"></script>
<script src="./introduction.js"></script> <script src="./introduction.js"></script>
<script src="./varaible.js"></script> <script src="./variable.js"></script>
<script src="./main.js"></script> <script src="./main.js"></script>
</body> </body>

@ -231,6 +231,10 @@ console.log(Math.E) // 2.718
console.log(Math.log(2)) // 0.6931471805599453 console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046 console.log(Math.log(10)) // 2.302585092994046
// Returns the natural logarithm of 2 and 10 respectively
console.log(Math.LN2) // 0.6931471805599453
console.log(Math.LN10) // 2.302585092994046
// Trigonometry // Trigonometry
Math.sin(0) Math.sin(0)
Math.sin(60) Math.sin(60)
@ -876,7 +880,7 @@ console.log(numFloat) // 9.81
let num = '9.81' let num = '9.81'
let numFloat = +num let numFloat = +num
console.log(numInt) // 9.81 console.log(numFloat) // 9.81
``` ```
#### Float to Int #### Float to Int

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript</title> <title>30DaysOfJavaScript</title>

@ -14,7 +14,7 @@ let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"] 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 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 txt = 'In 2019, I run 30 Days of Python. 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 let regEx = /\d/g // d with escape character means d not a normal d instead acts a digit
// + means one or more digit numbers, // + means one or more digit numbers,
// if there is g after that it means global, search everywhere. // if there is g after that it means global, search everywhere.

@ -1,5 +1,5 @@
// split(): The split method splits a string at a specified place. // split(): The split method splits a string at a specified place.
let string = '30 Days Of JavaScipt' let string = '30 Days Of JavaScript'
console.log(string.split()) // ["30 Days Of JavaScript"] console.log(string.split()) // ["30 Days Of JavaScript"]
console.log(string.split(' ')) // ["30", "Days", "Of", "JavaScript"] console.log(string.split(' ')) // ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh' let firstName = 'Asabeneh'

@ -31,7 +31,7 @@
- [Increment Operator](#increment-operator) - [Increment Operator](#increment-operator)
- [Decrement Operator](#decrement-operator) - [Decrement Operator](#decrement-operator)
- [Ternary Operators](#ternary-operators) - [Ternary Operators](#ternary-operators)
- [Operator Precendence](#operator-precendence) - [Operator Precedence](#operator-precedence)
- [Window Methods](#window-methods) - [Window Methods](#window-methods)
- [Window alert() method](#window-alert-method) - [Window alert() method](#window-alert-method)
- [Window prompt() method](#window-prompt-method) - [Window prompt() method](#window-prompt-method)
@ -73,7 +73,7 @@ We agreed that boolean values are either true or false.
### Truthy values ### Truthy values
- All numbers(positive and negative) are truthy except zero - All numbers(positive and negative) are truthy except zero
- All strings are truthy - All strings are truthy except an empty string ('')
- The boolean true - The boolean true
### Falsy values ### Falsy values
@ -254,7 +254,7 @@ let isMarried = !false // true
### Increment Operator ### Increment Operator
In JavaScrip we use the increment operator to increase a value stored in a variable. The increment could be pre or post increment. Let us see each of them: In JavaScript we use the increment operator to increase a value stored in a variable. The increment could be pre or post increment. Let us see each of them:
1. Pre-increment 1. Pre-increment
@ -276,7 +276,7 @@ We use most of the time post-increment. At least you should remember how to use
### Decrement Operator ### Decrement Operator
In JavaScrip we use the decrement operator to decrease a value stored in a variable. The decrement could be pre or post decrement. Let us see each of them: In JavaScript we use the decrement operator to decrease a value stored in a variable. The decrement could be pre or post decrement. Let us see each of them:
1. Pre-decrement 1. Pre-decrement
@ -333,9 +333,9 @@ number > 0
-5 is a negative number -5 is a negative number
``` ```
### Operator Precendence ### Operator Precedence
I would like to recommend you to read about operator precendence from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) I would like to recommend you to read about operator precedence from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
## Window Methods ## Window Methods
@ -382,7 +382,7 @@ These are not all the window methods we will have a separate section to go deep
## Date Object ## Date Object
Time is an important thing. We like to know the time a certain activity or event. In JavaScript current time and date is created using JavaScript Date Object. The object we create using Date object provides many methods to work with date and time.The methods we use to get date and time information from a date object values are started with a word _get_ because it provide the information. Time is an important thing. We like to know the time a certain activity or event. In JavaScript current time and date is created using JavaScript Date Object. The object we create using Date object provides many methods to work with date and time.The methods we use to get date and time information from a date object values are started with a word _get_ because it provide the information.
_getFullYear(), getMonths(), getDate(), getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_ _getFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_
![Date time Object](../images/date_time_object.png) ![Date time Object](../images/date_time_object.png)
@ -553,7 +553,7 @@ console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
```sh ```sh
Enter base: 20 Enter base: 20
Enter height: 10 Enter height: 10
The area of the triangle is 50 The area of the triangle is 100
``` ```
1. Write a script that prompt the user to enter side a, side b, and side c of the triangle and and calculate the perimeter of triangle (perimeter = a + b + c) 1. Write a script that prompt the user to enter side a, side b, and side c of the triangle and and calculate the perimeter of triangle (perimeter = a + b + c)
@ -568,9 +568,9 @@ console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
1. Get length and width using prompt and calculate an area of rectangle (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width)) 1. Get length and width using prompt and calculate an area of rectangle (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width))
1. Get radius using prompt and calculate the area of a circle (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14. 1. Get radius using prompt and calculate the area of a circle (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14.
1. Calculate the slope, x-intercept and y-intercept of y = 2x -2 1. Calculate the slope, x-intercept and y-intercept of y = 2x -2
1. Slope is (m = y2-y1/x2-x1). Find the slope between point (2, 2) and point(6,10) 1. Slope is m = (y<sub>2</sub>-y<sub>1</sub>)/(x<sub>2</sub>-x<sub>1</sub>). Find the slope between point (2, 2) and point(6,10)
1. Compare the slope of above two questions. 1. Compare the slope of above two questions.
1. Calculate the value of y (y = x^2 + 6x + 9). Try to use different x values and figure out at what x value y is 0. 1. Calculate the value of y (y = x<sup>2</sup> + 6x + 9). Try to use different x values and figure out at what x value y is 0.
1. Writ a script that prompt a user to enter hours and rate per hour. Calculate pay of the person? 1. Writ a script that prompt a user to enter hours and rate per hour. Calculate pay of the person?
```sh ```sh
@ -616,7 +616,7 @@ console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years 1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years
```sh ```sh
Enter number of yours you live: 100 Enter number of years you live: 100
You lived 3153600000 seconds. You lived 3153600000 seconds.
``` ```

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript: 03 Day</title> <title>30DaysOfJavaScript: 03 Day</title>

@ -21,7 +21,7 @@
- [Conditionals](#conditionals) - [Conditionals](#conditionals)
- [If](#if) - [If](#if)
- [If Else](#if-else) - [If Else](#if-else)
- [If Else if Else](#if-else-if-else) - [If Else if Else](#if--else-if-else)
- [Switch](#switch) - [Switch](#switch)
- [Ternary Operators](#ternary-operators) - [Ternary Operators](#ternary-operators)
- [💻 Exercises](#-exercises) - [💻 Exercises](#-exercises)
@ -190,6 +190,7 @@ switch(caseValue){
break break
case 3: case 3:
// code // code
break
default: default:
// code // code
} }
@ -279,7 +280,7 @@ isRaining
### Exercises: Level 1 ### 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. 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 needs to turn 18.
```sh ```sh
Enter your age: 30 Enter your age: 30

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript</title> <title>30DaysOfJavaScript</title>

@ -13,7 +13,7 @@
</sub> </sub>
</div> </div>
[<< Day 4](../04_Day_Conditionals/04_day_Conditionals.md) | [Day 6 >>](../06_Day_Loops/06_day_loops.md) [<< Day 4](../04_Day_Conditionals/04_day_conditionals.md) | [Day 6 >>](../06_Day_Loops/06_day_loops.md)
![Day 5](../images/banners/day_1_5.png) ![Day 5](../images/banners/day_1_5.png)
@ -390,22 +390,22 @@ Check an element if it exist in an array.
const fruits = ['banana', 'orange', 'mango', 'lemon'] const fruits = ['banana', 'orange', 'mango', 'lemon']
let index = fruits.indexOf('banana') // 0 let index = fruits.indexOf('banana') // 0
if(index != -1){ if(index === -1){
console.log('This fruit does exist in the array')
} else {
console.log('This fruit does not exist in the array') console.log('This fruit does not exist in the array')
} else {
console.log('This fruit does exist in the array')
} }
// This fruit does exist in the array // This fruit does exist in the array
// we can use also ternary here // 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') index === -1 ? console.log('This fruit does not exist in the array'): console.log('This fruit does exist in the array')
// let us check if a avocado exist in the array // let us check if a avocado exist in the array
let indexOfAvocado = fruits.indexOf('avocado') // -1, if the element not found index is -1 let indexOfAvocado = fruits.indexOf('avocado') // -1, if the element not found index is -1
if(indexOfAvocado!= -1){ if(indexOfAvocado === -1){
console.log('This fruit does exist in the array')
} else {
console.log('This fruit does not exist in the array') console.log('This fruit does not exist in the array')
} else {
console.log('This fruit does exist in the array')
} }
// This fruit does not exist in the array // This fruit does not exist in the array
``` ```

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:05 Day </title> <title>30DaysOfJavaScript:05 Day </title>

@ -108,7 +108,7 @@ const numbers = [1, 2, 3, 4, 5]
const newArr = [] const newArr = []
let sum = 0 let sum = 0
for(let i = 0; i < numbers.length; i++){ for(let i = 0; i < numbers.length; i++){
newArr.push(i * i) newArr.push( numbers[i] ** 2)
} }
@ -178,7 +178,9 @@ for (const num of numbers) {
// adding all the numbers in the array // adding all the numbers in the array
let sum = 0 let sum = 0
for (const num of numbers) { for (const num of numbers) {
sum += sum + num // can be also shorten like this, sum += num sum = sum + num
// can be also shorten like this, sum += num
// after this we will use the shorter synthax(+=, -=, *=, /= etc)
} }
console.log(sum) // 15 console.log(sum) // 15
@ -406,6 +408,7 @@ for(let i = 0; i <= 5; i++){
['Germany', 'GER', 7], ['Germany', 'GER', 7],
['Hungary', 'HUN', 7], ['Hungary', 'HUN', 7],
['Ireland', 'IRE', 7], ['Ireland', 'IRE', 7],
['Iceland', 'ICE', 7],
['Japan', 'JAP', 5], ['Japan', 'JAP', 5],
['Kenya', 'KEN', 5] ['Kenya', 'KEN', 5]
] ]
@ -414,7 +417,7 @@ for(let i = 0; i <= 5; i++){
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'. 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 ```sh
['Finland', 'Iceland'] ['Finland','Ireland', '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'. 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'.

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:06 Day </title> <title>30DaysOfJavaScript:06 Day </title>

@ -239,7 +239,7 @@ function sumAllNums() {
console.log(arguments) console.log(arguments)
} }
sumAllNums(1, 2, 3, 4)) sumAllNums(1, 2, 3, 4)
// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ] // Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
``` ```
@ -269,7 +269,7 @@ console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173
const sumAllNums = (...args) => { const sumAllNums = (...args) => {
// console.log(arguments), arguments object not found in arrow function // console.log(arguments), arguments object not found in arrow function
// instead we use an a parameter followed by spread operator // instead we use a parameter followed by spread operator (...)
console.log(args) console.log(args)
} }
@ -502,10 +502,12 @@ console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gra
### Function declaration versus Arrow function ### Function declaration versus Arrow function
It ill be covered in other time It Will be covered in other section.
🌕 You are a rising star, now you knew function . Now, you are super charged with the power of functions. You have just completed day 7 challenges and you are 7 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. 🌕 You are a rising star, now you knew function . Now, you are super charged with the power of functions. You have just completed day 7 challenges and you are 7 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Exercises ## 💻 Exercises
### Exercises: Level 1 ### Exercises: Level 1
@ -521,7 +523,7 @@ It ill be covered in other time
9. Density of a substance is calculated as follows:_density= mass/volume_. Write a function which calculates _density_. 9. Density of a substance is calculated as follows:_density= mass/volume_. Write a function which calculates _density_.
10. Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, _speed_. 10. Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, _speed_.
11. Weight of a substance is calculated as follows: _weight = mass x gravity_. Write a function which calculates _weight_. 11. Weight of a substance is calculated as follows: _weight = mass x gravity_. Write a function which calculates _weight_.
12. Temperature in oC can be converted to oF using this formula: _oF = (oC x 9/5) + 32_. Write a function which convert oC to oF _convertCelciusToFahrenheit_. 12. Temperature in oC can be converted to oF using this formula: _oF = (oC x 9/5) + 32_. Write a function which convert oC to oF _convertCelsiusToFahrenheit_.
13. Body mass index(BMI) is calculated as follows: _bmi = weight in Kg / (height x height) in m2_. Write a function which calculates _bmi_. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is _underweight, normal, overweight_ or _obese_ based the information given below. 13. Body mass index(BMI) is calculated as follows: _bmi = weight in Kg / (height x height) in m2_. Write a function which calculates _bmi_. BMI is used to broadly define different weight groups in adults 20 years old or older.Check if a person is _underweight, normal, overweight_ or _obese_ based the information given below.
- The same groups apply to both men and women. - The same groups apply to both men and women.
@ -617,7 +619,7 @@ It ill be covered in other time
### Exercises: Level 3 ### Exercises: Level 3
1. Modify question number n . Declare a function name _userIdGeneratedByUser_. It doesnt take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated. 1. Modify the _userIdGenerator_ function. Declare a function name _userIdGeneratedByUser_. It doesnt take any parameter but it takes two inputs using prompt(). One of the input is the number of characters and the second input is the number of ids which are supposed to be generated.
```sh ```sh
userIdGeneratedByUser() userIdGeneratedByUser()

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:07 Day </title> <title>30DaysOfJavaScript:07 Day </title>

@ -19,7 +19,7 @@
- [📔 Day 8](#-day-8) - [📔 Day 8](#-day-8)
- [Scope](#scope) - [Scope](#scope)
- [Window Scope](#window-scope) - [Window Global Object](#window-global-object)
- [Global scope](#global-scope) - [Global scope](#global-scope)
- [Local scope](#local-scope) - [Local scope](#local-scope)
- [📔 Object](#-object) - [📔 Object](#-object)
@ -42,26 +42,25 @@
## Scope ## 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. 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 be declared at different scope. In this section, we will see the scope variables, scope of variables when we use var or let.
Variables scopes can be: Variables scopes can be:
- Window
- Global - Global
- Local - Local
Variable can be declared globally or locally or window scope. We will see both global and local scope. Variable can be declared globally or locally scope. We will see both global and local scope.
Anything declared without let, var or const is scoped at window level. Anything declared without let, var or const is scoped at global level.
Let us image we have a scope.js file. Let us imagine that we have a scope.js file.
### Window Scope ### Window Global Object
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. 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 ```js
//scope.js //scope.js
a = 'JavaScript' // is a window scope this found anywhere a = 'JavaScript' // declaring a variable without let or const make it available in window object and this found anywhere
b = 10 // this is a window scope variable b = 10 // this is a global scope variable and found in the window object
function letsLearnScope() { function letsLearnScope() {
console.log(a, b) console.log(a, b)
if (true) { if (true) {
@ -96,29 +95,36 @@ console.log(a, b) // JavaScript 10, accessible
A variable declared as local can be accessed only in certain block code. A variable declared as local can be accessed only in certain block code.
- Block Scope
- Function Scope
```js ```js
//scope.js //scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file 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 let b = 10 // is a global scope it will be found anywhere in this file
// Function scope
function letsLearnScope() { function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible console.log(a, b) // JavaScript 10, accessible
let c = 30 let value = false
// block scope
if (true) { if (true) {
// we can access from the function and outside the function but // we can access from the function and outside the function but
// variables declared inside the if will not be accessed outside the if block // variables declared inside the if will not be accessed outside the if block
let a = 'Python' let a = 'Python'
let b = 20 let b = 20
let c = 30
let d = 40 let d = 40
console.log(a, b, c) // Python 20 30 value = !value
console.log(a, b, c, value) // Python 20 30 true
} }
// we can not access c because c's scope is only the if block // we can not access c because c's scope is only the if block
console.log(a, b) // JavaScript 10 console.log(a, b, value) // JavaScript 10 true
} }
letsLearnScope() letsLearnScope()
console.log(a, b) // JavaScript 10, accessible 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 ({}). 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 block, etc). Block in JavaScript is a code in between two curly brackets ({}).
```js ```js
//scope.js //scope.js
@ -136,9 +142,9 @@ if (true){
console.log(gravity) // 9.81 console.log(gravity) // 9.81
for(var i = 0; i < 3; i++){ for(var i = 0; i < 3; i++){
console.log(i) // 1, 2, 3 console.log(i) // 0, 1, 2
} }
console.log(i) console.log(i) // 3
``` ```
@ -161,13 +167,13 @@ if (true){
// console.log(gravity), Uncaught ReferenceError: gravity is not defined // console.log(gravity), Uncaught ReferenceError: gravity is not defined
for(let i = 0; i < 3; i++){ for(let i = 0; i < 3; i++){
console.log(i) // 1, 2, 3 console.log(i) // 0, 1, 2
} }
// console.log(i), Uncaught ReferenceError: gravity is not defined // console.log(i), Uncaught ReferenceError: i 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. The scope *let* and *const* are the same. The difference is only reassigning. We can not change or reassign the value of the `const` variable. I would strongly suggest you to use *let* and *const*, by using *let* and *const* you will write 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 an array, object, arrow function and function expression.
## 📔 Object ## 📔 Object
@ -250,14 +256,14 @@ const person = {
console.log(person.firstName) console.log(person.firstName)
console.log(person.lastName) console.log(person.lastName)
console.log(person.age) console.log(person.age)
console.log(person.location) console.log(person.location) // undefined
// value can be accessed using square bracket and key name // value can be accessed using square bracket and key name
console.log(person['firstName']) console.log(person['firstName'])
console.log(person['lastName']) console.log(person['lastName'])
console.log(person['age']) console.log(person['age'])
console.log(person['age']) console.log(person['age'])
console.log(person['location']) console.log(person['location']) // undefined
// for instance to access the phone number we only use the square bracket method // for instance to access the phone number we only use the square bracket method
console.log(person['phone number']) console.log(person['phone number'])

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:08 Day </title> <title>30DaysOfJavaScript:08 Day </title>

@ -22,9 +22,9 @@
- [Higher Order Function](#higher-order-function) - [Higher Order Function](#higher-order-function)
- [Callback](#callback) - [Callback](#callback)
- [Returning function](#returning-function) - [Returning function](#returning-function)
- [setting time](#setting-time) - [Setting time](#setting-time)
- [setInterval](#setinterval) - [Setting Interval using a setInterval function](#setting-interval-using-a-setinterval-function)
- [setTimeout](#settimeout) - [Setting a time using a setTimeout](#setting-a-time-using-a-settimeout)
- [Functional Programming](#functional-programming) - [Functional Programming](#functional-programming)
- [forEach](#foreach) - [forEach](#foreach)
- [map](#map) - [map](#map)
@ -54,12 +54,12 @@ Higher order functions are functions which take other function as a parameter or
A callback is a function which can be passed as parameter to other function. See the example below. A callback is a function which can be passed as parameter to other function. See the example below.
```js ```js
// a callback function, the function could be any name // a callback function, the name of the function could be any name
const callback = (n) => { const callback = (n) => {
return n ** 2 return n ** 2
} }
// function take other function as a callback // function that takes other function as a callback
function cube(callback, n) { function cube(callback, n) {
return callback(n) * n return callback(n) * n
} }
@ -71,7 +71,6 @@ console.log(cube(callback, 3))
Higher order functions return function as a value Higher order functions return function as a value
```js ```js
// Higher order function returning an other function // Higher order function returning an other function
const higherOrder = n => { const higherOrder = n => {
@ -81,7 +80,6 @@ const higherOrder = n => {
} }
return doWhatEver return doWhatEver
} }
return doSomething return doSomething
} }
console.log(higherOrder(2)(3)(10)) console.log(higherOrder(2)(3)(10))
@ -91,13 +89,12 @@ Let us see were we use call back functions.For instance the _forEach_ method use
```js ```js
const numbers = [1, 2, 3, 4] const numbers = [1, 2, 3, 4]
const sumArray = arr => { const sumArray = arr => {
let sum = 0 let sum = 0
const callBack = function(element) { const callback = function(element) {
sum += element sum += element
} }
numbers.forEach(callback) arr.forEach(callback)
return sum return sum
} }
@ -115,7 +112,7 @@ const numbers = [1, 2, 3, 4]
const sumArray = arr => { const sumArray = arr => {
let sum = 0 let sum = 0
numbers.forEach(function(element) { arr.forEach(function(element) {
sum += element sum += element
}) })
return sum return sum
@ -128,20 +125,20 @@ console.log(sumArray(numbers))
15 15
``` ```
### setting time ### Setting time
In JavaScript we can execute some activity on certain interval of time or we can schedule(wait) for sometime to execute some activities. In JavaScript we can execute some activities in a certain interval of time or we can schedule(wait) for some time to execute some activities.
- setInterval - setInterval
- setTimeout - setTimeout
#### setInterval #### Setting Interval using a setInterval function
In JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. The setInterval global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback will be always called in that interval of time. In JavaScript, we use setInterval higher order function to do some activity continuously with in some interval of time. The setInterval global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback will be always called in that interval of time.
```js ```js
// syntax // syntax
function callBack() { function callback() {
// code goes here // code goes here
} }
setInterval(callback, duration) setInterval(callback, duration)
@ -151,10 +148,10 @@ setInterval(callback, duration)
function sayHello() { function sayHello() {
console.log('Hello') console.log('Hello')
} }
setInterval(sayHello, 2000) // it prints hello in every 2 seconds setInterval(sayHello, 1000) // it prints hello in every second, 1000ms is 1s
``` ```
#### setTimeout #### Setting a time using a setTimeout
In JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time. In JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time.
@ -196,8 +193,7 @@ arr.forEach((element, index, arr) => console.log(index, element, arr))
```js ```js
let sum = 0; let sum = 0;
const numbers = [1, 2, 3, 4, 5]; const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num))) numbers.forEach(num => console.log(num))
console.log(sum) console.log(sum)
``` ```
@ -212,7 +208,7 @@ console.log(sum)
```js ```js
let sum = 0; let sum = 0;
const numbers = [1, 2, 3, 4, 5]; const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => sum += num)) numbers.forEach(num => sum += num)
console.log(sum) console.log(sum)
``` ```
@ -349,18 +345,19 @@ console.log(countriesHaveFiveLetters)
```js ```js
const scores = [ const scores = [
{ name: 'Asabeneh', score: 95 }, { name: 'Asabeneh', score: 95 },
{ name: 'Lidiya', score: 98 },
{ name: 'Mathias', score: 80 }, { name: 'Mathias', score: 80 },
{ name: 'Elias', score: 50 }, { name: 'Elias', score: 50 },
{ name: 'Martha', score: 85 }, { name: 'Martha', score: 85 },
{ name: 'John', score: 100 }, { name: 'John', score: 100 },
] ]
const scoresGreaterEight = scores.filter((score) => score.score > 80) const scoresGreaterEighty = scores.filter((score) => score.score > 80)
console.log(scoresGreaterEight) console.log(scoresGreaterEighty)
``` ```
```sh ```sh
[{name: 'Asabeneh', score: 95}, {name: 'Martha', score: 85},{name: 'John', score: 100}] [{name: 'Asabeneh', score: 95}, { name: 'Lidiya', score: 98 },{name: 'Martha', score: 85},{name: 'John', score: 100}]
``` ```
### reduce ### reduce
@ -391,9 +388,9 @@ _every_: Check if all the elements are similar in one aspect. It returns boolean
```js ```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'] const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const areAllStr = names.every((name) => typeof name === 'string') const areAllStr = names.every((name) => typeof name === 'string') // Are all strings?
console.log(arrAllStr) console.log(areAllStr)
``` ```
```sh ```sh
@ -402,9 +399,7 @@ true
```js ```js
const bools = [true, true, true, true] const bools = [true, true, true, true]
const areAllTrue = bools.every((b) => { const areAllTrue = bools.every((b) => b === true) // Are all true?
return b === true
})
console.log(areAllTrue) // true console.log(areAllTrue) // true
``` ```
@ -448,9 +443,7 @@ const scores = [
{ name: 'John', score: 100 }, { name: 'John', score: 100 },
] ]
const score = scores.find((user) => { const score = scores.find((user) => user.score > 80)
return user.score > 80
})
console.log(score) console.log(score)
``` ```
@ -481,15 +474,13 @@ _some_: Check if some of the elements are similar in one aspect. It returns bool
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook'] const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const bools = [true, true, true, true] const bools = [true, true, true, true]
const areSomeTrue = bools.some((b) => { const areSomeTrue = bools.some((b) => b === true)
return b === true
})
console.log(areSomeTrue) //true console.log(areSomeTrue) //true
``` ```
```js ```js
const areAllStr = names.some((name) => typeof name === 'number') const areAllStr = names.some((name) => typeof name === 'number') // Are all strings ?
console.log(areAllStr) // false console.log(areAllStr) // false
``` ```
@ -580,7 +571,7 @@ const products = [
``` ```
1. Explain the difference between **_forEach, map, filter, and reduce_**. 1. Explain the difference between **_forEach, map, filter, and reduce_**.
2. Define a call function before you them in forEach, map, filter or reduce. 2. Define a callback function before you use it in forEach, map, filter or reduce.
3. Use **_forEach_** to console.log each country in the countries array. 3. Use **_forEach_** to console.log each country in the countries array.
4. Use **_forEach_** to console.log each name in the names array. 4. Use **_forEach_** to console.log each name in the names array.
5. Use **_forEach_** to console.log each number in the numbers array. 5. Use **_forEach_** to console.log each number in the numbers array.

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:09 Day </title> <title>30DaysOfJavaScript:09 Day </title>

@ -71,8 +71,8 @@ const languages = [
'French', 'French',
] ]
const setOfLangauges = new Set(languages) const setOfLanguages = new Set(languages)
console.log(setOfLangauges) console.log(setOfLanguages)
``` ```
```sh ```sh
@ -92,9 +92,9 @@ const languages = [
'French', 'French',
] ]
const setOfLangauges = new Set(languages) const setOfLanguages = new Set(languages)
for (const language of setOfLangauges) { for (const language of setOfLanguages) {
console.log(language) console.log(language)
} }
``` ```
@ -241,12 +241,11 @@ console.log(C)
```sh ```sh
Set(6) {1, 2, 3, 4, 5,6} Set(6) {1, 2, 3, 4, 5,6}
``` ```
### Intersection of sets ### Intersection of sets
To find an intersection of two sets can be achieved using filter. Lets find the union of set A and set B (A ∩ B) To find an intersection of two sets can be achieved using filter. Lets find the intersection of set A and set B (A ∩ B)
```js ```js
let a = [1, 2, 3, 4, 5] let a = [1, 2, 3, 4, 5]
@ -263,7 +262,6 @@ console.log(C)
```sh ```sh
Set(3) {3, 4, 5} Set(3) {3, 4, 5}
``` ```
### Difference of sets ### Difference of sets
@ -285,7 +283,6 @@ console.log(C)
```sh ```sh
Set(2) {1, 2} Set(2) {1, 2}
``` ```
## Map ## Map
@ -372,7 +369,7 @@ for (const country of countriesMap) {
(2) ["Norway", "Oslo"] (2) ["Norway", "Oslo"]
``` ```
```sh ```js
for (const [country, city] of countriesMap){ for (const [country, city] of countriesMap){
console.log(country, city) console.log(country, city)
} }
@ -391,8 +388,8 @@ Norway Oslo
### Exercises:Level 1 ### Exercises:Level 1
```js ```js
const a = {4, 5, 8, 9} const a = [4, 5, 8, 9]
const b = {3, 4, 5, 7} const b = [3, 4, 5, 7]
const countries = ['Finland', 'Sweden', 'Norway'] const countries = ['Finland', 'Sweden', 'Norway']
``` ```
@ -417,8 +414,9 @@ const countries = ['Finland', 'Sweden', 'Norway']
```js ```js
// Your output should look like this // Your output should look like this
console.log(mostSpokenLanguages(countries, 10))[ console.log(mostSpokenLanguages(countries, 10))
({ English: 91 }, [
{ English: 91 },
{ French: 45 }, { French: 45 },
{ Arabic: 25 }, { Arabic: 25 },
{ Spanish: 24 }, { Spanish: 24 },
@ -428,19 +426,16 @@ const countries = ['Finland', 'Sweden', 'Norway']
{ German: 7 }, { German: 7 },
{ Chinese: 5 }, { Chinese: 5 },
{ Swahili: 4 }, { Swahili: 4 },
{ Serbian: 4 }) { Serbian: 4 }
] ]
// Your output should look like this // Your output should look like this
console.log(mostSpokenLanguages(countries, 3)) console.log(mostSpokenLanguages(countries, 3))
```
[ [
{'English':91}, {English:91},
{'French':45}, {French:45},
{'Arabic':25} {Arabic:25}
] ]
``` ```
@ -448,4 +443,3 @@ const countries = ['Finland', 'Sweden', 'Norway']
[<< Day 9](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) | [Day 11 >>](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) [<< Day 9](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) | [Day 11 >>](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md)
```

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:10 Day </title> <title>30DaysOfJavaScript:10 Day </title>

@ -59,7 +59,7 @@ Destructuring is a way to unpack arrays, and objects and assigning to a distinct
const names = ['Asabeneh', 'Brook', 'David', 'John'] const names = ['Asabeneh', 'Brook', 'David', 'John']
let [firstPerson, secondPerson, thirdPerson, fourthPerson] = names let [firstPerson, secondPerson, thirdPerson, fourthPerson] = names
console.log(firstName, secondPerson,thirdPerson, fourthPerson) console.log(firstPerson, secondPerson,thirdPerson, fourthPerson)
``` ```
```sh ```sh
@ -209,7 +209,7 @@ const rectangle = {
height: 10, height: 10,
area: 200 area: 200
} }
let { width: w, heigh: h, area: a, perimeter: p } = rectangle let { width: w, height: h, area: a, perimeter: p } = rectangle
console.log(w, h, a, p) console.log(w, h, a, p)
``` ```
@ -226,7 +226,7 @@ const rectangle = {
height: 10, height: 10,
area: 200 area: 200
} }
let { width, heigh, area, perimeter = 60 } = rectangle let { width, height, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //20 10 200 60 console.log(width, height, area, perimeter) //20 10 200 60
//Lets modify the object:width to 30 and perimeter to 80 //Lets modify the object:width to 30 and perimeter to 80
@ -239,8 +239,8 @@ const rectangle = {
area: 200, area: 200,
perimeter: 80 perimeter: 80
} }
let { width, heigh, area, perimeter = 60 } = rectangle let { width, height, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //20 10 200 80 console.log(width, height, area, perimeter) //30 10 200 80
``` ```
Destructuring keys as a function parameters. Lets create a function which take a rectangle object and it return a perimeter of a rectangle. Destructuring keys as a function parameters. Lets create a function which take a rectangle object and it return a perimeter of a rectangle.

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:11 Day </title> <title>30DaysOfJavaScript:11 Day </title>

@ -25,7 +25,7 @@
- [Creating a pattern with RegExp Constructor](#creating-a-pattern-with-regexp-constructor) - [Creating a pattern with RegExp Constructor](#creating-a-pattern-with-regexp-constructor)
- [Creating a pattern without RegExp Constructor](#creating-a-pattern-without-regexp-constructor) - [Creating a pattern without RegExp Constructor](#creating-a-pattern-without-regexp-constructor)
- [RegExpp Object Methods](#regexpp-object-methods) - [RegExpp Object Methods](#regexpp-object-methods)
- [Testing for a match](#testing-for-a-match) - [Testing for a match](#testing-for--a-match)
- [Array containing all of the match](#array-containing-all-of-the-match) - [Array containing all of the match](#array-containing-all-of-the-match)
- [Replacing a substring](#replacing-a-substring) - [Replacing a substring](#replacing-a-substring)
- [Square Bracket](#square-bracket) - [Square Bracket](#square-bracket)
@ -503,22 +503,19 @@ distance = 12
```js ```js
sentence = `%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?` sentence = `%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?`
console.log(cleanText(sentence)) console.log(cleanText(sentence))
``` ```
```sh ```sh
I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher
``` ```
1. Write a function which find the most frequent words. After cleaning, count three most frequent words in the string. 2. Write a function which find the most frequent words. After cleaning, count three most frequent words in the string.
```js ```js
console.log(mostFrequentWords(cleanedText)) console.log(mostFrequentWords(cleanedText))
[{word:'I', count:3}, {word:'teaching', count:2}, {word:'teacher', count:2}] [{word:'I', count:3}, {word:'teaching', count:2}, {word:'teacher', count:2}]
``` ```
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 11](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | [Day 13 >>](../13_Day_Console_object_methods/13_day_console_object_methods.md) [<< Day 11](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | [Day 13 >>](../13_Day_Console_object_methods/13_day_console_object_methods.md)

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:11 Day </title> <title>30DaysOfJavaScript:11 Day </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:13 Day </title> <title>30DaysOfJavaScript:13 Day </title>

@ -113,7 +113,7 @@ throw new Error('Required') // generates an error object with the message of Req
``` ```
```js ```js
const throwErroExampleFun = () => { const throwErrorExampleFun = () => {
let message let message
let x = prompt('Enter a number: ') let x = prompt('Enter a number: ')
try { try {
@ -126,7 +126,7 @@ const throwErroExampleFun = () => {
console.log(err) console.log(err)
} }
} }
throwErroExampleFun() throwErrorExampleFun()
``` ```
### Error Types ### Error Types

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:12 Day </title> <title>30DaysOfJavaScript:12 Day </title>

@ -111,7 +111,7 @@ console.log(person)
``` ```
```sh ```sh
Person {firstName: undefined, lastName} Person {firstName: undefined, lastName:undefined}
``` ```
All the keys of the object are undefined. When ever we instantiate we should pass the value of the properties. Let us pass value at this time when we instantiate the class. All the keys of the object are undefined. When ever we instantiate we should pass the value of the properties. Let us pass value at this time when we instantiate the class.
@ -305,7 +305,7 @@ class Person {
const fullName = this.firstName + ' ' + this.lastName const fullName = this.firstName + ' ' + this.lastName
return fullName return fullName
} }
get getscore() { get getScore() {
return this.score return this.score
} }
get getSkills() { get getSkills() {

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:15 Day </title> <title>30DaysOfJavaScript:15 Day </title>

@ -63,7 +63,7 @@ JSON stands for JavaScript Object Notation. The JSON syntax is derived from Java
} }
``` ```
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. The above JSON example is not much different from 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. 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.
@ -177,6 +177,10 @@ Mostly we fetch JSON data from HTTP response or from a file, but we can store th
JSON.parse(json[, reviver]) JSON.parse(json[, reviver])
// json or text , the data // json or text , the data
// reviver is an optional callback function // reviver is an optional callback function
/* JSON.parse(json, (key, value) => {
})
*/
``` ```
```js ```js
@ -440,7 +444,7 @@ const user = {
country: 'Finland', country: 'Finland',
city: 'Helsinki', city: 'Helsinki',
email: 'alex@alex.com', email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Pyhton'], skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Python'],
age: 250, age: 250,
isLoggedIn: false, isLoggedIn: false,
points: 30 points: 30
@ -576,11 +580,8 @@ const txt = `{
### Exercises Level 1 ### Exercises Level 1
1. Change skills array to JSON using JSON.stringify() 1. Change skills array to JSON using JSON.stringify()
1. Stringify the age variable 1. Stringify the age variable
1. Stringify the isMarried variable 1. Stringify the isMarried variable
1. Stringify the student object 1. Stringify the student object
### Exercises Level 2 ### Exercises Level 2
@ -590,7 +591,7 @@ const txt = `{
### Exercises Level 3 ### Exercises Level 3
1. Parse the *txt* JSON to object. 1. Parse the *txt* JSON to object.
2. Find the the user who has many skills from the variable stored in *txt*. 2. Find the user who has many skills from the variable stored in *txt*.
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:16 Day </title> <title>30DaysOfJavaScript:16 Day </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:17 Day </title> <title>30DaysOfJavaScript:17 Day </title>

@ -38,7 +38,7 @@
Web Storage(sessionStorage and localStorage) is a new HTML5 API offering important benefits over traditional cookies. Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. The data storage limit of cookies in many web browsers is about 4 KB per cookie. We Storages can store far larger data (at least 5MB) and never transferred to the server. All sites from the same or one origin can store and access the same data. Web Storage(sessionStorage and localStorage) is a new HTML5 API offering important benefits over traditional cookies. Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. The data storage limit of cookies in many web browsers is about 4 KB per cookie. We Storages can store far larger data (at least 5MB) and never transferred to the server. All sites from the same or one origin can store and access the same data.
The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases. The are are two Web Storage objects: The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases. There are two Web Storage objects:
- sessionStorage - sessionStorage
- localStorage - localStorage
@ -77,7 +77,7 @@ For the examples mentioned above, it makes sense to use localStorage. You may be
In cases, we want to to get rid of the data as soon as the window is closed. Or, perhaps, if we do not want the application to interfere with the same application thats open in another window. These scenarios are served best with sessionStorage. In cases, we want to to get rid of the data as soon as the window is closed. Or, perhaps, if we do not want the application to interfere with the same application thats open in another window. These scenarios are served best with sessionStorage.
Now, let use how use make use of these Web Storage APIs. Now, let us see how make use of these Web Storage APIs.
## HTML5 Web Storage Objects ## HTML5 Web Storage Objects
@ -90,7 +90,7 @@ Web Storage objects:
- _localStorage_ - to display the localStorage object - _localStorage_ - to display the localStorage object
- _localStorage.clear()_ - to remove everything in the local storage - _localStorage.clear()_ - to remove everything in the local storage
- _localStorage.setItem()_ - to storage data in the localStorage. It takes a key and a value parameters. - _localStorage.setItem()_ - to store data in the localStorage. It takes a key and a value parameters.
- _localStorage.getItem()_ - to display data stored in the localStorage. It takes a key as a parameter. - _localStorage.getItem()_ - to display data stored in the localStorage. It takes a key as a parameter.
- _localStorage.removeItem()_ - to remove stored item form a localStorage. It takes key as a parameter. - _localStorage.removeItem()_ - to remove stored item form a localStorage. It takes key as a parameter.
- _localStorage.key()_ - to display a data stored in a localStorage. It takes index as a parameter. - _localStorage.key()_ - to display a data stored in a localStorage. It takes index as a parameter.

@ -73,7 +73,6 @@ const callback = (err, result) => {
} }
doSomething(callback) doSomething(callback)
``` ```
```sh ```sh
@ -106,7 +105,7 @@ doSomething((err, result) => {
### Promise constructor ### Promise constructor
We can create a promise using the Promise constructor. We can create a new promise using the key word new followed by the word Promise and followed by a parenthesis. Inside the parenthesis it it takes a callback function. The promise callback function has two parameters which are the *resolve* and *reject* functions. We can create a promise using the Promise constructor. We can create a new promise using the key word `new` followed by the word `Promise` and followed by a parenthesis. Inside the parenthesis, it takes a `callback` function. The promise callback function has two parameters which are the _`resolve`_ and _`reject`_ functions.
```js ```js
// syntax // syntax
@ -148,7 +147,7 @@ doPromise
const doPromise = new Promise((resolve, reject) => { const doPromise = new Promise((resolve, reject) => {
setTimeout(() => { setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS'] const skills = ['HTML', 'CSS', 'JS']
if (skills.indexOf('Node') !== -1) { if (skills.includes('Node')) {
resolve('fullstack developer') resolve('fullstack developer')
} else { } else {
reject('Something wrong has happened') reject('Something wrong has happened')
@ -160,7 +159,7 @@ doPromise
.then(result => { .then(result => {
console.log(result) console.log(result)
}) })
.catch(error => console.log(error)) .catch(error => console.error(error))
``` ```
```sh ```sh
@ -172,13 +171,14 @@ doPromise
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set. In this challenge we will use fetch to request url and APIS. In addition to that let us see demonstrate use case of promises in accessing network resources using the fetch API. The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set. In this challenge we will use fetch to request url and APIS. In addition to that let us see demonstrate use case of promises in accessing network resources using the fetch API.
```js ```js
const url = 'https://restcountries.eu/rest/v2/all' // countries api const url = 'https://restcountries.com/v2/all' // countries api
fetch(url) fetch(url)
.then(response => response.json()) // accessing the API data as JSON .then(response => response.json()) // accessing the API data as JSON
.then(data => { // getting the data .then(data => {
// getting the data
console.log(data) console.log(data)
}) })
.catch(error => console.log(error)) // handling error if something wrong happens .catch(error => console.error(error)) // handling error if something wrong happens
``` ```
## Async and Await ## Async and Await
@ -197,9 +197,9 @@ square(2)
Promise {<resolved>: 4} Promise {<resolved>: 4}
``` ```
The word *async* in front of a function means that function will return a promise. The above square function instead of a value it returned a promise. The word _async_ in front of a function means that function will return a promise. The above square function instead of a value it returned a promise.
How do we access the value from the promise? To access the value from the promise, we will use the keyword *await*. How do we access the value from the promise? To access the value from the promise, we will use the keyword _await_.
```js ```js
const square = async function (n) { const square = async function (n) {
@ -219,13 +219,13 @@ Let us fetch API data using both promise method and async and await method.
- promise - promise
```js ```js
const url = 'https://restcountries.eu/rest/v2/all' const url = 'https://restcountries.com/v2/all'
fetch(url) fetch(url)
.then(response => response.json()) .then(response => response.json())
.then(data => { .then(data => {
console.log(data) console.log(data)
}) })
.catch(error => console.log(error)) .catch(error => console.error(error))
``` ```
- async and await - async and await
@ -237,19 +237,19 @@ const fetchData = async () => {
const countries = await response.json() const countries = await response.json()
console.log(countries) console.log(countries)
} catch (err) { } catch (err) {
console.log(err) console.error(err)
} }
} }
console.log('===== async and await') console.log('===== async and await')
fetchData() fetchData()
``` ```
🌕 You are real and you kept your promise and your reached to day 18. Keep your promise and settle the challenge with resolve. You are 18 steps a head to your way to greatness. Now do some exercises for your brain and for your muscle. 🌕 You are real and you kept your promise and you reached to day 18. Keep your promise and settle the challenge with resolve. You are 18 steps ahead to your way to greatness. Now do some exercises for your brain and muscles.
## Exercises ## Exercises
```js ```js
const countriesAPI = 'https://restcountries.eu/rest/v2/all' const countriesAPI = 'https://restcountries.com/v2/all'
const catsAPI = 'https://api.thecatapi.com/v1/breeds' const catsAPI = 'https://api.thecatapi.com/v1/breeds'
``` ```

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:18 Day </title> <title>30DaysOfJavaScript:18 Day </title>

@ -14,7 +14,7 @@
</div> </div>
[<< Day 18](../18_Day_Promises/18_day_promise.md) | [Day 20 >>](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) [<< Day 18](../18_Day_Promises/18_day_promises.md) | [Day 20 >>](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md)
![Thirty Days Of JavaScript](../images/banners/day_1_19.png) ![Thirty Days Of JavaScript](../images/banners/day_1_19.png)
- [Day 19](#day-19) - [Day 19](#day-19)
@ -80,7 +80,7 @@ console.log(innerFuncs.minusOne)
```sh ```sh
1 1
1 0
``` ```
🌕 You are making progress. Maintain your momentum, keep the good work. Now do some exercises for your brain and for your muscle. 🌕 You are making progress. Maintain your momentum, keep the good work. Now do some exercises for your brain and for your muscle.
@ -101,4 +101,4 @@ console.log(innerFuncs.minusOne)
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 18](../18_Day_Promises/18_day_promise.md) | [Day 20 >>](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) [<< Day 18](../18_Day_Promises/18_day_promises.md) | [Day 20 >>](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md)

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:19 Day </title> <title>30DaysOfJavaScript:19 Day </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:20 Day </title> <title>30DaysOfJavaScript:20 Day </title>

@ -140,10 +140,10 @@ const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
By now you are very familiar function declaration, expression function, arrow function and anonymous function. In this challenge we tend to use arrow function instead of other functions. Arrow function is not a replacement for other functions. In addition, arrow functions and function declarations are not exactly the same. So you should know when to use and when not. I will cover the difference in detail in other sections. We will use explicit return instead of implicit return if the function is one liner By now you are very familiar function declaration, expression function, arrow function and anonymous function. In this challenge we tend to use arrow function instead of other functions. Arrow function is not a replacement for other functions. In addition, arrow functions and function declarations are not exactly the same. So you should know when to use and when not. I will cover the difference in detail in other sections. We will use explicit return instead of implicit return if the function is one liner
```js ```js
// function which prints full name of a person // function which return full name of a person
const printFullName = (firstName, lastName) => firstName + ' ' + lastName const printFullName = (firstName, lastName) => firstName + ' ' + lastName
// function which calculate a square of a number // function which calculates a square of a number
const square = (n) => n * n const square = (n) => n * n
// a function which generate random hexa colors // a function which generate random hexa colors
@ -180,6 +180,8 @@ const showDateTime = () => {
} }
``` ```
The `new Dat().toLocaleString()` can also be used to display current date time. The `toLocaleString()` methods takes different arguments. You may learn more about date and time from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString).
#### Loops #### Loops
We coverer many types of loops in this challenges. The regular for loop, while loop, do while loop, for of loop, forEach loop and for in loop. We coverer many types of loops in this challenges. The regular for loop, while loop, do while loop, for of loop, forEach loop and for in loop.
@ -196,7 +198,7 @@ const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
// iterating an array using regular for loop // iterating an array using regular for loop
let len = names.length; let len = names.length;
for(let i = 0; i < len; i++){ for(let i = 0; i < len; i++){
console.log(names[i].toUpperCas()) console.log(names[i].toUpperCase())
} }
@ -218,7 +220,7 @@ const person = {
skills: ['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js'], skills: ['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js'],
isMarried: true isMarried: true
} }
for(const key in user) { for(const key in person) {
console.log(key) console.log(key)
} }
@ -236,7 +238,7 @@ const person = {
age: 250, age: 250,
country: 'Finland', country: 'Finland',
city: 'Helsinki', city: 'Helsinki',
skills: ['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js'], skills: ['HTML','CSS','JavaScript','TypeScript', 'React','Node','MongoDB','Python','D3.js'],
isMarried: true isMarried: true
} }
// iterating through object keys // iterating through object keys
@ -244,7 +246,6 @@ for(const key in person) {
console.log(key, person[key]) console.log(key, person[key])
} }
``` ```
#### Conditional #### Conditional

@ -32,7 +32,7 @@
- [Removing class using remove](#removing-class-using-remove) - [Removing class using remove](#removing-class-using-remove)
- [Adding Text to HTML element](#adding-text-to-html-element) - [Adding Text to HTML element](#adding-text-to-html-element)
- [Adding Text content using textContent](#adding-text-content-using-textcontent) - [Adding Text content using textContent](#adding-text-content-using-textcontent)
- [Adding Text Content using innHTML](#adding-text-content-using-innhtml) - [Adding Text Content using innerHTML](#adding-text-content-using-innerhtml)
- [Text Content](#text-content) - [Text Content](#text-content)
- [Inner HTML](#inner-html) - [Inner HTML](#inner-html)
- [Adding style](#adding-style) - [Adding style](#adding-style)
@ -57,7 +57,7 @@ We can access already created element or elements using JavaScript. To access or
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>Document Object Model</title> <title>Document Object Model</title>
</head> </head>
@ -74,7 +74,7 @@ We can access already created element or elements using JavaScript. To access or
#### Getting elements by tag name #### Getting elements by tag name
**_getElementsByTagName()_**:takes a take name as a string parameter and this method returns an HTMLCollection object. An HTMLCollection is an array like object of HTML elements. The length property provides the size of the collection. Whenever we use this method we access the individual elements using index or after loop through each individual items. An HTMLCollection does not support all array methods therefore we should use regular for loop instead of forEach. **_getElementsByTagName()_**:takes a tag name as a string parameter and this method returns an HTMLCollection object. An HTMLCollection is an array like object of HTML elements. The length property provides the size of the collection. Whenever we use this method we access the individual elements using index or after loop through each individual items. An HTMLCollection does not support all array methods therefore we should use regular for loop instead of forEach.
```js ```js
// syntax // syntax
@ -84,7 +84,7 @@ document.getElementsByTagName('tagname')
```js ```js
const allTitles = document.getElementsByTagName('h1') const allTitles = document.getElementsByTagName('h1')
console.log(allTitles) //HTMCollections console.log(allTitles) //HTMLCollections
console.log(allTitles.length) // 4 console.log(allTitles.length) // 4
for (let i = 0; i < allTitles.length; i++) { for (let i = 0; i < allTitles.length; i++) {
@ -104,7 +104,7 @@ document.getElementsByClassName('classname')
```js ```js
const allTitles = document.getElementsByClassName('title') const allTitles = document.getElementsByClassName('title')
console.log(allTitles) //HTMCollections console.log(allTitles) //HTMLCollections
console.log(allTitles.length) // 4 console.log(allTitles.length) // 4
for (let i = 0; i < allTitles.length; i++) { for (let i = 0; i < allTitles.length; i++) {
@ -133,9 +133,9 @@ The _document.querySelector_ method can select an HTML or HTML elements by tag n
**_querySelector_**: can be used to select HTML element by its tag name, id or class. If the tag name is used it selects only the first element. **_querySelector_**: can be used to select HTML element by its tag name, id or class. If the tag name is used it selects only the first element.
```js ```js
let firstTitle = document.querySelector('h1') // select the first available h2 element let firstTitle = document.querySelector('h1') // select the first available h1 element
let firstTitle = document.querySelector('#first-title') // select id with first-title let firstTitle = document.querySelector('#first-title') // select id with first-title
let firstTitle = document.querySelector('.title') // select the first available h2 element with class title let firstTitle = document.querySelector('.title') // select the first available h1 element with class title
``` ```
**_querySelectorAll_**: can be used to select html element by its tag name or class. It return a nodeList which is an array like object which support array methods. We can use **_for loop_** or **_forEach_** to loop through each nodeList elements. **_querySelectorAll_**: can be used to select html element by its tag name or class. It return a nodeList which is an array like object which support array methods. We can use **_for loop_** or **_forEach_** to loop through each nodeList elements.
@ -158,7 +158,7 @@ An attribute is added in the opening tag of HTML which gives additional informat
```js ```js
const titles = document.querySelectorAll('h1') const titles = document.querySelectorAll('h1')
titles[3].class = 'title' titles[3].className = 'title'
titles[3].id = 'fourth-title' titles[3].id = 'fourth-title'
``` ```
@ -214,7 +214,7 @@ const titles = document.querySelectorAll('h1')
titles[3].textContent = 'Fourth Title' titles[3].textContent = 'Fourth Title'
``` ```
#### Adding Text Content using innHTML #### Adding Text Content using innerHTML
Most people get confused between _textContent_ and _innerHTML_. _textContent_ is meant to add text to an HTML element, however innerHTML can add a text or HTML element or elements as a child. Most people get confused between _textContent_ and _innerHTML_. _textContent_ is meant to add text to an HTML element, however innerHTML can add a text or HTML element or elements as a child.
@ -234,7 +234,7 @@ It value we assign is going to be a string of HTML elements.
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>JavaScript for Everyone:DOM</title> <title>JavaScript for Everyone:DOM</title>
</head> </head>
@ -264,7 +264,7 @@ The innerHTML property can allow us also to remove all the children of a parent
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>JavaScript for Everyone:DOM</title> <title>JavaScript for Everyone:DOM</title>
</head> </head>
@ -378,7 +378,7 @@ As you have notice, the properties of css when we use it in JavaScript is going
```html ```html
<!-- index.html --> <!-- index.html -->
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>JavaScript for Everyone:DOM</title> <title>JavaScript for Everyone:DOM</title>
</head> </head>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:21 Day </title> <title>30DaysOfJavaScript:21 Day </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:22 Day: Number Generator </title> <title>30DaysOfJavaScript:22 Day: Number Generator </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:22 Day: World Countries List</title> <title>30DaysOfJavaScript:22 Day: World Countries List</title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:22 Day: Challenge Info</title> <title>30DaysOfJavaScript:22 Day: Challenge Info</title>

@ -174,7 +174,7 @@ By now you are familiar with addEventListen method and how to attach event liste
List of events: List of events:
- click - when the element clicked - click - when the element clicked
- dbclick - when the element double clicked - dblclick - when the element double clicked
- mouseenter - when the mouse point enter to the element - mouseenter - when the mouse point enter to the element
- mouseleave - when the mouse pointer leave the element - mouseleave - when the mouse pointer leave the element
- mousemove - when the mouse pointer move on the element - mousemove - when the mouse pointer move on the element

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:23 Day: Number Generator </title> <title>30DaysOfJavaScript:23 Day: Number Generator </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:23 Day: Keyboard Key </title> <title>30DaysOfJavaScript:23 Day: Keyboard Key </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>Solar System: Document Object Model:30 Days Of JavaScript</title> <title>Solar System: Document Object Model:30 Days Of JavaScript</title>

@ -1,5 +1,5 @@
<div align="center"> <div align="center">
<h1> 30 Days Of JavaScript: World Countrires Data Visualization</h1> <h1> 30 Days Of JavaScript: World Countries Data Visualization</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/"> <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"> <img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a> </a>
@ -14,7 +14,7 @@
</div> </div>
[<< Day 24](../24_Day_Project_soloar_system/24_day_project_soloar_system.md) | [Day 26 >>](../26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) [<< Day 24](../24_Day_Project_solar_system/24_day_project_solar_system.md) | [Day 26 >>](../26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md)
![Thirty Days Of JavaScript](../images/banners/day_1_25.png) ![Thirty Days Of JavaScript](../images/banners/day_1_25.png)

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:11 Day </title> <title>30DaysOfJavaScript:11 Day </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:11 Day </title> <title>30DaysOfJavaScript:11 Day </title>

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:11 Day </title> <title>30DaysOfJavaScript:11 Day </title>

@ -14,7 +14,7 @@
</div> </div>
[<< Day 28](../28_Day_Mini_project_animating_characters/28_day_mini_project_animating_characters.md) | [Day 30>>](../30_Day_Mini_project_final/30_day_mini_project_final.md) [<< Day 28](../28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | [Day 30>>](../30_Day_Mini_project_final/30_day_mini_project_final.md)
![Thirty Days Of JavaScript](../images/banners/day_1_29.png) ![Thirty Days Of JavaScript](../images/banners/day_1_29.png)
@ -41,4 +41,4 @@
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 28](../28_Day_Mini_project_animating_characters/28_day_mini_project_animating_characters.md) | [Day 30>>](../30_Day_Mini_project_final/30_day_mini_project_final.md) [<< Day 28](../28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | [Day 30>>](../30_Day_Mini_project_final/30_day_mini_project_final.md)

@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript: Day 29 - Project 2 </title> <title>30DaysOfJavaScript: Day 29 - Project 2 </title>

@ -17,7 +17,7 @@
<div> <div>
<small>Support [**Asabeneh**](https://www.patreon.com/asabeneh?fan_landing=true) to create more educational materials</small> <small>Support [**Asabeneh**](https://www.patreon.com/asabeneh?fan_landing=true) to create more educational materials</small>
[<img src = '../images/become_patreon.png' alt='become-asabeneh-patreon' title='click' />](https://www.patreon.com/asabeneh?fan_landing=true)
</div> </div>
@ -30,6 +30,7 @@
- [Exercise: Level 1](#exercise-level-1) - [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2) - [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3) - [Exercise: Level 3](#exercise-level-3)
- [Testimony](#testimony)
# Day 30 # Day 30
@ -39,7 +40,7 @@
1. Create the following animation using (HTML, CSS, JS) 1. Create the following animation using (HTML, CSS, JS)
![Countries daata](./../images/projects/dom_mini_project_countries_object_day_10.1.gif) ![Countries data](./../images/projects/dom_mini_project_countries_object_day_10.1.gif)
2. Validate the following form using regex. 2. Validate the following form using regex.
@ -54,6 +55,10 @@
🌕 Your journey to greatness completed successfully. You reached high level of greatness. Now, you are much greater than ever before. I knew what it takes to reach to this level and you made to this point. You are a real hero. Now, it is time to celebrate your success with a friend or with a family. I am looking forward to seeing you in an other challenge. 🌕 Your journey to greatness completed successfully. You reached high level of greatness. Now, you are much greater than ever before. I knew what it takes to reach to this level and you made to this point. You are a real hero. Now, it is time to celebrate your success with a friend or with a family. I am looking forward to seeing you in an other challenge.
## Testimony
Now it is time to express your thoughts about the Author and 30DaysOfJavaScript. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/)
~![Congratulations](./../images/projects/congratulations.gif) ~![Congratulations](./../images/projects/congratulations.gif)
[<< Day 29](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) [<< Day 29](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md)

@ -0,0 +1,637 @@
# 자바스크립트 30일 정복 😎
| # Day | Topics |
| ----- | :--------------------------------------------------------------------------------------------------------------------------------------: |
| 01 | [소개](./readMe.md) |
| 02 | [자료형](./02_Day_Data_types/02_day_data_types.md) |
| 03 | [불리언, 연산자, 날짜](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) |
| 04 | [조건문](./04_Day_Conditionals/04_day_conditionals.md) |
| 05 | [배열](./05_Day_Arrays/05_day_arrays.md) |
| 06 | [반복문](./06_Day_Loops/06_day_loops.md) |
| 07 | [함수](./07_Day_Functions/07_day_functions.md) |
| 08 | [객체](./08_Day_Objects/08_day_objects.md) |
| 09 | [고차 함수](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) |
| 10 | [집합과 맵](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) |
| 11 | [구조 분해 할당과 전개 연산자](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) |
| 12 | [정규표현식](./12_Day_Regular_expressions/12_day_regular_expressions.md) |
| 13 | [콘솔 객체 메서드](./13_Day_Console_object_methods/13_day_console_object_methods.md) |
| 14 | [오류 핸들링](./14_Day_Error_handling/14_day_error_handling.md) |
| 15 | [클래스](./15_Day_Classes/15_day_classes.md) |
| 16 | [JSON](./16_Day_JSON/16_day_json.md) |
| 17 | [웹 저장소](./17_Day_Web_storages/17_day_web_storages.md) |
| 18 | [프로미스](./18_Day_Promises/18_day_promises.md) |
| 19 | [클로져](./19_Day_Closures/19_day_closures.md) |
| 20 | [클린 코드 작성법](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) |
| 21 | [DOM](./21_Day_DOM/21_day_dom.md) |
| 22 | [DOM 객체 조작](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) |
| 23 | [이벤트 리스너](./23_Day_Event_listeners/23_day_event_listeners.md) |
| 24 | [미니 프로젝트: 태양계](./24_Day_Project_solar_system/24_day_project_solar_system.md) |
| 25 | [미니 프로젝트: 세계 도시 데이터 시각화 1](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) |
| 26 | [미니 프로젝트: 세계 도시 데이터 시각화 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) |
| 27 | [미니 프로젝트: 포트폴리오](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) |
| 28 | [미니 프로젝트: 리더보드](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) |
| 29 | [미니 프로젝트: 캐릭터 움직이기](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) |
| 30 | [최종 프로젝트](./30_Day_Mini_project_final/30_day_mini_project_final.md) |
🇬🇧 [English](../readMe.md)
🇪🇸 [Spanish](../Spanish/readme.md)
🇷🇺 [Russian](../RU/README.md)
[2일차 >>](./02_Day_Data_types/02_day_data_types.md)
![Thirty Days Of JavaScript](../images/day_1_1.png)
- [자바스크립트 30일 정복](#30-days-of-javascript)
- [📔 1일차](#📔-1일차)
- [소개](#소개)
- [요구 사항](#요구사항)
- [설정](#설정)
- [Node.js 설치](#Node.js-설치)
- [브라우저](#브라우저)
- [구글 크롬 설치](#구글-크롬-설치)
- [구글 크롬 콘솔창 열기](#구글-크롬-콘솔창-열기)
- [콘솔창에서 코드 작성해 보기](#콘솔창에서-코드-작성해-보기)
- [Console.log로 출력하기](#Console.log로-출력하기)
- [Console.log로 여러 인자 출력하기](#Console.log로-여러-인자-출력하기)
- [주석](#주석)
- [문법](#문법)
- [산술](#산술)
- [코드 편집기](#코드-편집기)
- [Visual Studio Code 설치](#Visual-Studio-Code-설치)
- [Visual Studio Code 사용법](#Visual-Studio-Code-사용법)
- [웹 페이지에서 자바스크립트 코드 적용](#웹-페이지에서-자바스크립트-코드-적용)
- [인라인 자바스크립트](#인라인-자바스크립트)
- [내부 자바스크립트](#내부-자바스크립트)
- [외부 자바스크립트](#외부-자바스크립트)
- [여러 외부 자바스크립트](#여러-외부-자바스크립트)
- [자료형 소개](#자료형-소개)
- [숫자](#숫자)
- [문자열](#문자열)
- [불리언](#불리언)
- [Undefined](#Undefined)
- [Null](#Null)
- [자료형 확인하기](#자료형-확인하기)
- [주석을 다시](#주석을-다시)
- [변수](#변수)
- [💻 1일차: 실습](#-1일차-실습)
# 📔 1일차
## 소개
자바스크립트 30일 정복 프로그래밍 챌린지에 참여 결정하신 것을 축하드립니다. 이번 챌린지에서는 자바스크립트 프로그래머가 되기 위해서 필요한 모든 것들과, 일반적인 프로그래밍에 대한 개념을 다룹니다. 해당 챌린지를 모두 완료하셨다면, 30DaysOfJavaScript 프로그래밍 챌린지 완료 인증서를 받게 됩니다. 도움이 필요하거나, 다른 사람을 도와주고 싶은 경우 [텔레그램 그룹](https://t.me/ThirtyDaysOfJavaScript)에 연락을 주세요.
**자바스크립트 30일 정복 챌린지**는 초보자와 숙련된 자바스크립트 개발자를 위한 지침서입니다. 자바스크립트에 오신 것을 환영합니다. 자바스크립트는 웹을 다루는 언어입니다. 저는 여러분들을 가르치고 사용하는 것을 즐깁니다. 여러분도 그렇게 되셨으면 좋겠습니다.
자바스크립트 30일 정복 챌린지를 단계별로 진행하면서, 인류 역사상 가장 인기있는 자바스크립트를 배우게 될 것입니다.
자바스크립트는 **_상호작용을 하는 웹사이트를 만들거나, 모바일 애플리케이션 혹은 데스크탑 애플리케이션, 게임_**을 만드는 데에 사용이 됩니다. 요즈음 자바스크립트는 **_머신러닝과 AI_**를 하는데에도 사용이 됩니다. **_자바스크립트(JS)_**는 최근 몇 년간 인기가 상승하여 선두를 달리고 있습니다. 실제로 깃헙에서 6년동안 가장 많이 사용되고 있습니다.
## 요구사항
프로그래밍에 대한 선수 지식은 해당 챌린지에서 필요하지 않습니다. 대신 아래에 대한 요구사항이 필요합니다.
1. 열정
2. 컴퓨터
3. 인터넷
4. 브라우저
5. 코드 편집기
## 설정
저는 여러분이 개발자, 컴퓨터, 인터넷이 되기 위해서 강한 욕구와 동기부여가 있다고 믿습니다. 만약 이런 것들을 가지고 있다면, 해당 챌린지를 시작할 수 있습니다.
### Node.js 설치
여러분은 Node.js가 당장은 필요 없지만, 나중을 위해 설치가 필요합니다. [해당 사이트](https://nodejs.org/en/)에서 설치를 진행해 주세요.
![노드 다운로드](../images/download_node.png)
다운로드가 끝이 나면 파일을 더블 클릭해서 열고 설치합니다.
![노드 설치](../images/install_node.png)
우리의 로컬 컴퓨터에 터미널 창을 열거나, 명령 프롬포트를 통해서 노드가 설치되어 있는지 알 수 있습니다.
```sh
asabeneh $ node -v
v12.14.0
```
해당 챌린지을 제작할 때에는 Node 12.14.0 버전을 사용했으나, 현재는 Node 14.17.6 버전을 권장하고 있습니다.
### 브라우저
브라우저는 많은 것들이 존재합니다. 그러나, 우리는 구글 크롬을 강력하게 권장합니다.
#### 구글 크롬 설치
[구글 크롬](https://www.google.com/chrome/)이 설치되어있지 않다면, 설치를 해 주세요. 우리는 브라우저 콘솔창에서 간단한 자바스크립트 코드를 작성할 수 있습니다. 그러나 우리는 애플리케이션을 개발하기 위해 브라우저 콘솔을 사용하지 않습니다.
![구글 크롬](../images/google_chrome.png)
#### 구글 크롬 콘솔창 열기
브라우저 오른쪽 상단에 있는 점 3개를 클릭하고 **추가 도구 -> 개발자 도구**를 선택하거나 바로 가기 키를 사용하여 구글 크롬 콘솔창을 열 수 있습니다. 저는 단축키 사용을 선호합니다.
![Opening chrome](../images/opening_developer_tool.png)
콘솔창을 열기위한 단축키는 아래와 같습니다.
```sh
Mac
Command+Option+J
Windows/Linux:
Ctl+Shift+J
```
![Opening console](../images/opening_chrome_console_shortcut.png)
콘솔창을 열고 나서, 표시된 버튼을 경험해 보세요. 우리는 콘솔창에서 많은 시간을 보내게 될 것 입니다. 콘솔창은 자바스크립트 코드가 저장되는 위치입니다. 구글 크롬의 콘솔창의 V8 엔진은 자바스크립트 코드를 기계 코드로 변경시켜줍니다.
콘솔창에서 간단한 자바스크립트 코드 예제를 적어봅시다.
![write code on console](../images/js_code_on_chrome_console.png)
#### 콘솔창에서 코드 작성해 보기
우리는 구글 크롬이 아니더라도, 콘솔창에서 간단한 코드를 작성해볼 수 있습니다. 그러나 이 챌린지를 위해서는 오직 구글 크롬 콘솔창에만 집중합시다. 콘솔창을 열어 주세요.
```sh
Mac
Command+Option+I
Windows:
Ctl+Shift+I
```
##### Console.log로 출력하기
우리의 첫 번째 코드는, 내장되어있는 함수인 **console.log()**입니다. 인수로 입력 데이터를 전달하면, 해당 함수가 결과물을 콘솔창에 표시합니다. 우리는 console.log() 함수에 'Hello, World'를 인풋으로 전달을 해 봅시다.
```js
console.log('Hello, World!');
```
##### Console.log로 여러 인자 출력하기
**console.log()** 함수는 반점(comma)로 여러개의 인자를 구분할 수 있습니다. 문법은 다음과 같습니다. **console.log(param1, param2, param3)**
![console log multiple arguments](../images/console_log_multipl_arguments.png)
```js
console.log('Hello', 'World', '!');
console.log('HAPPY', 'NEW', 'YEAR', 2020);
console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript');
```
위의 예시 코드와 같이, *console.log()*함수는 여러 인자를 사용할 수 있습니다.
축하드립니다! 당신은 *console.log()*를 이용해서 첫 자바스크립트 코드를 작성했습니다.
##### 주석
우리는 우리의 코드에 주석을 추가합니다. 주석은 코드의 가독성과, 코드의 설명을 남기는데에 매우 중요합니다. 자바스크립트는 코드 내부에 주석을 실행하지 않습니다. 자바스크립트에서 //로 시작하는 것은 주석이며, /\*로 시작해서 \*/로 닫히는 것 또한 주석이 될 수 있습니다.
**한 줄 주석 예시**
// 첫 번째 주석입니다.
// 두 번째 주석입니다.
// 한 줄 주석입니다.
**여러 줄 주석 예시**
/_
여러 줄 주석할 때 사용합니다.
여러줄 주석은 여러 줄을 입력할 수 있습니다.
자바스크립트는 웹을 다루는 프로그래밍 언어입니다.
_/
##### 문법
프로그래밍 언어는 인간의 언어와 유사합니다. 영어 혹은 다른 모든 언어는 단어부터 시작해서 문법, 문장, 복잡한 문장을 사용하고 의미있는 메시지들을 전달합니다. 영어에서의 구문의 의미는 언어에서 잘 만들어진 문장을 만들기 위한 단어와 문법의 배열입니다. 문법의 기술적인 정의는 컴퓨터 언어에서의 문장 구조입니다. 프로그래밍 언어에는 문법이 있습니다. 자바스크립트와, 다른 프로그래밍 언어는 문법을 가지고 있습니다. 우리는 자바스크립트가 이해할 수 있는 문법을 작성하지 않는다면, 해당 코드는 여러 가지 오류를 일으킬 것입니다. 오류에 대한 다양한 종류는 다음에 살펴봅시다. 지금부터는 간단한 문법 오류를 살펴봅시다.
![Error](../images/raising_syntax_error.png)
고의적으로 실수를 저질렀습니다. 그 결과 콘솔창은 구문 오류를 발생시키고 있습니다. 실제로 이런 구문은 매우 유익합니다. 어떤 실수가 일어났는지 알려줍니다. 오류 피드백에 대한 가이드라인을 읽으면서 우리는 구문을 수정하고 문제를 해결할 수 있습니다. 프로그램으로부터 발생한 오류를 구별하고 제거하는 과정을 디버깅이라고 말합니다. 아래 오류를 수정해 봅시다:
```js
console.log('Hello, World!');
console.log('Hello, World!');
```
지금까지, 우리는 _console.log()_ 함수를 통해서 문자열을 표시하는 방법을 다루었습니다. _console.log()_ 를 이용해서 문자열을 입력하려면 작은 따옴표나, 큰 따옴표 혹은 백틱 따옴표안에 들어가있어야 합니다.
**예시:**
```js
console.log('Hello, World!');
console.log('Hello, World!');
console.log(`Hello, World!`);
```
#### 산술
이번에는 구글 크롬 콘솔창에서 숫자 자료형을 _console.log()_ 로 작성하는 법에 대해서 공부해 봅시다.
문자열외에도 자바스크립트를 이용해서 수학적인 계산도 가능합니다. 다음과 같은 간단한 계산을 해 봅시다.
콘솔창은 **_console.log()_** 함수 없이 직접 인수를 사용할 수 있습니다. 그러나 앞선 말한 것은 함수 사용이 필수적인 텍스트 편집기에서 일어나기 때문에, 맨 앞 부분에 포함되어 있습니다. 콘솔창을 통해서 명령어들을 가지고 놀 수 있습니다.
![Arithmetic](../images/arithmetic.png)
```js
console.log(2 + 3); // 덧셈
console.log(3 - 2); // 뺄셈
console.log(2 * 3); // 곱셈
console.log(3 / 2); // 나눗셈
console.log(3 % 2); // 나눗셈 - 나머지 구하기
console.log(3 ** 2); // 제곱 3 ** 2 == 3 * 3
```
### 코드 편집기
우리는 브라우저의 콘솔에서 코드를 작성할 수 있지만, 큰 프로젝트에서는 바람직하지 않습니다. 실제 일하는 환경에서 개발자는 코드를 작성하기 위해서 서로 다른 코드 편집기를 사용합니다. 해당 자바스크립트 30일 정복 챌린지에서는 Visual Studio Code를 사용할 예정입니다.
#### Visual Studio Code 설치
Visual Studio Code는 매우 유명한 오픈 소스 텍스트 편집기입니다. 우리는 [Visual Studio Code](https://code.visualstudio.com/)를 다운로드 하는 것을 권장합니다. 그렇지만 다른 편집기가 마음에 든다면, 원하시는 대로 사용하면 됩니다.
![Vscode](../images/vscode.png)
Visual Studio Code를 설치했다면, 실제로 사용해 봅시다.
#### Visual Studio Code 사용법
Visual Studio Code의 아이콘을 더블 클릭해서 실행합시다. 실행이 되었다면 다음과 같은 화면을 볼 수 있습니다. 라벨이 적혀져있는 아이콘들을 사용해 봅시다.
![Vscode ui](../images/vscode_ui.png)
![Vscode add project](../images/adding_project_to_vscode.png)
![Vscode open project](../images/opening_project_on_vscode.png)
![script file](../images/scripts_on_vscode.png)
![Installing Live Server](../images/vsc_live_server.png)
![running script](../images/running_script.png)
![coding running](../images/launched_on_new_tab.png)
## 웹 페이지에서 자바스크립트 코드 적용
자바스크립트 코드는 웹 페이지에 세 가지 방법으로 적용할 수 있습니다:
- **인라인 자바스크립트**
- **내부 자바스크립트**
- **외부 자바스크립트**
- **여러 외부 자바스크립트**
해당 섹션에서는 웹페이지에 자바스크립트 코드를 추가하는 각 방법을 다룰 예정입니다.
### 인라인 자바스크립트
데스크탑 등 아무 곳에서 30DaysOfJS라는 이름으로 프로젝트 폴더를 만들어 주세요. 만들고 나서, **_index.html_**을 생성합시다. 아래의 코드를 붙여넣고 크롬과 같은 브라우저로 열어봅시다.
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript:Inline Script</title>
</head>
<body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!')">
클릭해 주세요
</button>
</body>
</html>
```
지금 첫 인라인 자바스크립트를 작성했습니다. 우리는 자바스크립트 내장 함수 _alert()_ 를 이용해서 경고 메시지가 뜨게할 수 있습니다.
### 내부 자바스크립트
내부 자바스크립트는 _head_ 혹은 _body_ 에서 작성할 수 있습니다. 그러나, HTML문서에서 body에 넣는 것이 더 선호 됩니다.
첫 번째로, 페이지의 head부분에 작성해 봅시다.
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript:Internal Script</title>
<script>
console.log('Welcome to 30DaysOfJavaScript');
</script>
</head>
<body></body>
</html>
```
우리는 위와 같이 내부 자바스크립트를 사용합니다. 위에서 언급했듯이, body부분에 자바스크립트 코드를 넣는 것이 더 선호됩니다.
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript:Internal Script</title>
</head>
<body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button>
<script>
console.log('Welcome to 30DaysOfJavaScript');
</script>
</body>
</html>
```
브라우저의 콘솔창을 열고 console.log()의 출력값을 확인해 봅시다.
![js code from vscode](../images/js_code_vscode.png)
### 외부 자바스크립트
내부 자바스크립트 방식과 유사하게, 외부 자바스크립트 방식은 header 혹은 body에 존재합니다. 그러나 이 역시 body에 적는 것이 선호됩니다.
우선, .js 확장자를 가진 자바스크립트 파일을 생성해야 합니다. .js 확장자로 끝나는 모든 파일은 자바스크립트 파일입니다. introduction.js 프로젝트 폴더 내부에 파일을 생성하고 아래와 같은 코드를 넣어 봅시다. 그리고 본문 하단에 이 .js파일을 연결해 봅시다.
```js
console.log('Welcome to 30DaysOfJavaScript');
```
_head_ 에서의 외부 자바스크립트:
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:External script</title>
<script src="introduction.js"></script>
</head>
<body></body>
</html>
```
_body_ 에서의 외부 자바스크립트:
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript:External script</title>
</head>
<body>
<!-- header 혹은 body 어디에 넣든 상관이 없습니다. -->
<!-- 그러나, 여기에 넣는 것이 선호되는 편입니다. -->
<script src="introduction.js"></script>
</body>
</html>
```
브라우저의 콘솔창을 열고 console.log()의 출력값을 확인해 봅시다.
### 여러 외부 자바스크립트
우리는 한 개의 웹 페이지에 여러 자바스크립트 파일을 연결할 수 있습니다.
프로젝트 폴더 내에 helloworld.js 파일을 생성하고 아래 코드를 작성해 봅시다.
```js
console.log('Hello, World!');
```
```html
<!DOCTYPE html>
<html>
<head>
<title>Multiple External Scripts</title>
</head>
<body>
<script src="./helloworld.js"></script>
<script src="./introduction.js"></script>
</body>
</html>
```
_main.js 파일은 다른 모든 자바스크립트 파일 아래에 있어야 합니다_ 이것은 매우 중요합니다.
![Multiple Script](../images/multiple_script.png)
## 자료형 소개
자바스크립트와 다른 프로그래밍 언어는 여러 자료형들이 있습니다. 다음은 자바스크립트 기본 자료형입니다: _문자열, 숫자, 불리언, undefined, null_ 추가로 _Symbol_ 이 있습니다.
### 숫자
- 정수 자료형: 정수 (음수, 0, 양수) 숫자
예시:
... -3, -2, -1, 0, 1, 2, 3 ...
- 실수 자료형: 소수 숫자
예시
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
### 문자열
작은 따옴표, 큰 따옴표, 백틱 따옴표 사이에 있는 한 개 혹은 그 이상의 모음입니다.
**예시:**
```js
'Asabeneh';
'Finland';
'JavaScript is a beautiful programming language';
'I love teaching';
'I hope you are enjoying the first day'`We can also create a string using a backtick`;
('A string could be just as small as one character as big as many pages');
```
### 불리언
불리언 자료형은 참값과 거짓값이 있습니다. 모든 비교는 참 혹은 거짓값을 갖는 불리언 값을 반환합니다.
불리언 자료형은 참 혹은 거짓입니다.
**예시:**
```js
true; // 불이 켜져있다면 값은 true입니다.
false; // 불이 꺼져있다면 값은 true입니다.
```
### Undefined
자바스크립트에서 변수에 아무 값도 할당하지 않으면, 변수는 undefined값을 가집니다. 덧붙여 얘가하면 함수가 아무 값도 반환하지 않으면, 그것은 undefined를 반환합니다.
```js
let firstName;
console.log(firstName); // undefined이다. 할당이 되지 않았기 때문이다.
```
### Null
자바스크립트에서 값이 비어있으면 변수는 null값을 가집니다.
```js
let emptyValue = null;
```
## 자료형 확인하기
특정 변수의 자료형을 확인하고 싶으면 **typeof** 연산자를 사용하면 됩니다. 예시를 확인해 봅시다.
```js
console.log(typeof 'Asabeneh'); // 문자열
console.log(typeof 5); // 숫자
console.log(typeof true); // 불리언
console.log(typeof null); // null
console.log(typeof undefined); // undefined
```
## 주석을 다시
자바스크립트는 다른 프로그래밍언어처럼 주석을 달 수 있던 것을 기억해 봅시다. 주석은 가독성을 위해서 매우 중요합니다.
주석에는 두 방법이 있습니다.
- _한 줄 주석_
- _여러 줄 주석_
한 줄 주석:
```js
// 한 줄 주석으로 코드 자체에 주석 달기
// let firstName = 'Asabeneh'; 한 줄 주석
// let lastName = 'Yetayeh'; 한 줄 주석
```
여러 줄 주석:
```js
/*
let location = 'Helsinki';
let age = 100;
let isMarried = true;
This is a Multiple line comment
*/
```
## 변수
변수는 데이터의 _컨테이너_ 입니다. 변수는 메모리 공간에 데이터를 저장할 때 사용합니다. 우리가 변수를 선언하면, 메모리가 할당이 됩니다. 변수에 값을 할당하면은, 메모리 주소는 데이터로 채워집니다. 변수를 선언하기 위해서는 _var_, _let_, _const_ 키워드를 사용합니다.
프로그램이 돌아가면서 변수의 값이 바뀌는 경우, _let_ 키워드를 사용합니다. 만약 변수의 값이 아예 바뀌지 않을 것이라면, _const_ 키워드를 사용합니다. 예로들어 PI, 국가명, 중력은 변하지 않으므로 _const_ 를 사용합니다. 우리는 이 챌린지에서 _var_ 키워드는 사용하지 않을 것이고, 사용하지 않는 것을 권장합니다. 그것은 많은 약점을 가지고 있고, 오류를 발생하기 쉬운 방법입니다. 각 키워드의 자세한 사항, 다른 범위(scope)에서 다음에 알아봅시다. 지금은 위에서 언급한 부분이면 충분합니다.
유효한 자바스크립트 변수 이름을 위해서는 아래와 같은 규칙을 따라야합니다:
- 숫자로 시작하지 않습니다.
- 달러 기호($), 밑줄(\_)을 제외한 특수문자를 사용하면 안됩니다.
- camelCase 네이밍 컨벤션을 따릅니다.
- 변수 이름 단어 사이에 공백이 없어야 합니다.
자바스크립트 변수를 올바르게 이름짓는 법을 예시를 통해 확인해 봅시다.
```js
firstName;
lastName;
country;
city;
capitalCity;
age;
isMarried;
first_name;
last_name;
is_married;
capital_city;
num1;
num_1;
_num_1;
$num1;
year2020;
year_2020;
```
첫 번째와 두 번째 변수들은 camelCase 네이밍컨벤션을 따릅니다. 우리 자료에서는 camelCase를 사용할 예정입니다.
다음은 적절하지 못한 예시입니다:
```sh
first-name
1_num
num_#_1
```
서로 다른 유형의 데이터로 변수를 선언합시다. 변수를 선언하렴녀 _let_, _const_ 키워드를 사용합니다. 변수 이름 뒤에 등호와 값을 사용해 봅시다.
```js
// Syntax
let nameOfVariable = value;
```
**Examples of declared variables**
```js
// 다른 자료형을 가지고 있는 변수 선언
let firstName = 'Asabeneh'; // 이름
let lastName = 'Yetayeh'; // 성
let country = 'Finland'; // 나라
let city = 'Helsinki'; // 수도
let age = 100; // 나이
let isMarried = true; // 결혼 여부
console.log(firstName, lastName, country, city, age, isMarried);
```
```sh
Asabeneh Yetayeh Finland Helsinki 100 true
```
```js
// 각각 다른 숫자 자료형 선언
let age = 100; // 정수 (나이)
const gravity = 9.81; // 실수 (중력)
const boilingPoint = 100; // 정수 (끓는 점)
const PI = 3.14; // 실수 (파이)
console.log(gravity, boilingPoint, PI);
```
```sh
9.81 100 3.14
```
```js
// 쉼표(,)를 통해 변수를 구분해서 정의할 수 있습니다.
let name = 'Asabeneh', // 이름
job = 'teacher', // 직업
live = 'Finland'; // 사는 곳
console.log(name, job, live);
```
```sh
Asabeneh teacher Finland
```
01-Day 폴더에서 _index.html_ 파일을 실행하면 다음과 같은 메시지가 나타납니다.
![Day one](../images/day_1.png)
🌕 당신은 대단합니다! 1일차 도전을 완료했고, 우리는 멋져지고 있습니다. 이제 뇌와 근육을 운동해 봅시다!
# 💻 1일차: 실습
1. 다음의 의미를 갖는 주석을 만들어 봅시다. _주석은 코드를 읽을 수 있게 만듭니다._
2. 또 다른 주석을 만들어 봅시다. _30DaysOfJavascript에_ 오신 것을 환영합니다.
3. 여러 줄 주석을 사용해 봅시다. _주석은 읽기 편하고, 재사용하기 쉽고, 정보를 담고 있습니다_
4. variable.js 파일을 만들고, 문자열 변수, 불리언 변수, undefined 변수, null 변수를 선언해 봅시다.
5. datatype.js 파일을 만들고 **_typeof_** 연산을 통해서 데이터의 자료형을 확인해 봅시다. 모든 변수를 확인합시다!
6. 값을 할당하지 않고 변수를 만들어 봅니다.
7. 값을 할당하면서 변수를 만들어 봅니다.
8. 변수 성, 이름, 결혼 여부, 사는 곳, 나이를 여러 줄로 선언해 봅시다.
9. 변수 성, 이름, 결혼 여부, 사는 곳, 나이를 각각 한 줄로 선언해 봅시다.
10. 두 변수 _myAge__yourAge_ 를 만들어서 초기값을 할당하고, 콘솔창에 띄어봅시다.
```sh
I am 25 years old.
You are 30 years old.
```
🎉 축하드립니다 ! 🎉
[Day 2 >>](./02_Day_Data_types/02_day_data_types.md)

@ -0,0 +1,128 @@
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
<link href="https://fonts.googleapis.com/css?family=Lato:300, 400,400i,700,700i&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500&display=swap" rel="stylesheet">
</head>
<body>
<div class="wrapper">
<h1>Asabeneh Yetayeh challenges in <span>2020</span></h1>
<h2>30DaysOfJavaScript Challenge</h2>
<p></p>
<ul>
<li>30DaysOfPython Challenge Done</li>
<li>30DaysOfJavaScript Challenge Ongoing</li>
<li>30DaysOfReact Challenge Coming</li>
<li>30DaysOfReactNative Challenge Coming</li>
<li>30DaysOfFullStack Challenge Coming</li>
<li>30DaysOfDataAnalysis Challenge Coming</li>
<li>30DaysOfMachineLearning Challenge Coming</li>
</ul>
</div>
<script>
const hexaColor = () => {
const str = '0123456789abcdef'
let hexa = '#'
let index
for (let i = 0; i < 6; i++) {
index = Math.floor(Math.random() * str.length)
hexa += str[index]
}
return hexa
}
const showDateTime = () => {
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
const now = new Date()
const year = now.getFullYear()
const month = months[now.getMonth()]
const date = now.getDate()
let hours = now.getHours()
let minutes = now.getMinutes()
let seconds = now.getSeconds()
if (hours < 10) {
hours = '0' + hours
}
if (minutes < 10) {
minutes = '0' + minutes
}
if (seconds < 10) {
seconds = '0' + seconds
}
const dateMonthYear = `${month} ${date}, ${year}`
const time = hours + ':' + minutes
const fullTime = dateMonthYear + ' ' + time
return fullTime + `:${seconds}`
}
const wrapper = document.querySelector('.wrapper')
const year = document.querySelector('span')
const time = document.querySelector('p')
wrapper.style.width = '50%'
wrapper.style.margin = 'auto'
const title = document.querySelector('h1')
const subTitle = document.querySelector('h2')
title.style.textAlign = 'center'
title.style.fontFamily = 'Montserrat'
title.style.fontWeight = 500
subTitle.style.textAlign = 'center'
subTitle.style.fontFamily = 'Montserrat'
subTitle.style.fontWeight = 300
subTitle.style.textDecoration = 'underline'
time.style.textAlign = 'center'
time.style.fontFamily = 'Montserrat'
time.style.fontWeight = 400
setInterval(() => {
year.style.color = hexaColor()
year.style.fontSize = '96px'
year.style.fontWeight = 700;
time.textContent = showDateTime()
time.style.background = hexaColor()
time.style.width = "25%"
time.style.margin = 'auto'
time.style.padding = '10px'
}, 1000)
const ul = document.querySelector('ul')
const lists = document.querySelectorAll('li')
for (const list of lists) {
list.style.listStyle = 'none'
list.style.padding = '25px'
list.style.margin = '3px'
list.style.fontFamily = 'Montserrat'
list.style.fontWeight = 300;
list.style.letterSpacing = '0.0625em'
if (list.textContent.includes('Done')) {
list.style.background = '#21bf73'
} else if (list.textContent.includes('Ongoing')) {
list.style.background = '#fddb3a'
} else {
list.style.background = '#fd5e53'
}
}
</script>
</body>
</html>

@ -180,7 +180,7 @@ console.log("Welcome", "to", 30, "Days", "Of", "JavaScript");
Мы добавляем комментарии к нашему коду. Комментарии очень важны, чтобы сделать код более читабельным и оставить комментарии в нашем коде. JavaScript не выполняет часть комментариев нашего кода. Любой текст, начинающийся с `//` в JavaScript, является комментарием или что-то в этом роде `/* */` является комментарием. Мы добавляем комментарии к нашему коду. Комментарии очень важны, чтобы сделать код более читабельным и оставить комментарии в нашем коде. JavaScript не выполняет часть комментариев нашего кода. Любой текст, начинающийся с `//` в JavaScript, является комментарием или что-то в этом роде `/* */` является комментарием.
**Пример: Однострочный комментарийt** **Пример: Однострочный комментарий**
```js ```js
// Это первый комментарий // Это первый комментарий

@ -68,7 +68,7 @@
**30 días de JavaScript** es una guía tanto para principiantes como para desarrolladores avanzados. Bienvenido a JavaScript. Disfruto de usarlo y enseñarlo y espero que tú también. JavaScript es el lenguaje del navegador. **30 días de JavaScript** es una guía tanto para principiantes como para desarrolladores avanzados. Bienvenido a JavaScript. Disfruto de usarlo y enseñarlo y espero que tú también. JavaScript es el lenguaje del navegador.
En este tutorial de paso a paso, aprenderás JavaScript, el leguaje de programación más popular de la historia de la humanidad. Se usa para **agregar interactividad a las páginas web, para desarrollar aplicaciones móbiles, aplicaciones de desktop, juegos** y ahora también puede ser usado para el **aprendizaje automático** (machine learning) e **inteligencia artificial** (AI). Su popularidad ha incrementado en años recientes, siendo el lenguaje predominante por cuatro años consecutivos y el más usado en GitHub. En este tutorial de paso a paso, aprenderás JavaScript, el lenguaje de programación más popular de la historia de la humanidad. Se usa para **agregar interactividad a las páginas web, para desarrollar aplicaciones móviles, aplicaciones de desktop, juegos** y ahora también puede ser usado para el **aprendizaje automático** (machine learning) e **inteligencia artificial** (AI). Su popularidad ha incrementado en años recientes, siendo el lenguaje predominante por cuatro años consecutivos y el más usado en GitHub.
## Requerimientos ## Requerimientos
@ -99,7 +99,7 @@ Puedes comprobar si se ha instalado correctamente abriendo la terminal del orden
asabeneh $ node -v asabeneh $ node -v
v12.14.0 v12.14.0
Para el desafío estaremos utilizando la versión 12.14.0, la cual es la recomendada por node. Para el desafío estaremos utilizando la versión 12.14.0, la cual es la recomendada por Node.
### Navegador ### Navegador
@ -163,7 +163,7 @@ Como pueden ver, en el código del fragmento de arriba, console.log() puede toma
##### Comentario ##### Comentario
Podemos añadir comentarios a nuestro código. Los comentarios son muy importantes para hacer el código más legible y para dejar recordatorios en nuestro código. JavaScript no ejecuta la parte de comentarios de nuestro código. Cualquier hay texto que empiece con // en JavaScript es un comentario o cualquier cosa que encierre como esta /\* \*/ es un comentario. Podemos añadir comentarios a nuestro código. Los comentarios son muy importantes para hacer el código más legible y para dejar recordatorios en nuestro código. JavaScript no ejecuta la parte de comentarios de nuestro código. Cualquier texto que empiece con // en JavaScript es un comentario o cualquier cosa que encierre como esta /\* \*/ es un comentario.
**Ejemplo: Comentario en una sola línea** **Ejemplo: Comentario en una sola línea**
@ -371,8 +371,8 @@ En JavaScript y también en otros lenguajes de programación, hay diferentes tip
Una colección de uno o más carácteres entre comillas. **Ejemplo:** Una colección de uno o más carácteres entre comillas. **Ejemplo:**
"Asabeneh "Asabeneh"
"Finlandia "Finlandia"
'JavaScript es un hermoso lenguaje de programación'. 'JavaScript es un hermoso lenguaje de programación'.
"Me encanta enseñar" "Me encanta enseñar"
"Espero que estés disfrutando del primer día" "Espero que estés disfrutando del primer día"

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -59,8 +59,10 @@
🇬🇧 [English](./readMe.md) 🇬🇧 [English](./readMe.md)
🇪🇸 [Spanish](./Spanish/readme.md) 🇪🇸 [Spanish](./Spanish/readme.md)
🇷🇺 [Russian](./RU/README.md) 🇷🇺 [Russian](./RU/README.md)
KR [Korian](./Korea/README.md)
ᴢʜ [Chinese](./ZH/README.md) ᴢʜ [Chinese](./ZH/README.md)
</div> </div>
</div> </div>
@ -134,7 +136,7 @@ I believe you have the motivation and a strong desire to be a developer, a compu
### Install Node.js ### Install Node.js
You may not need node.js right now but you may need it for later. Install [node.js](https://nodejs.org/en/). You may not need Node.js right now but you may need it for later. Install [node.js](https://nodejs.org/en/).
![Node download](images/download_node.png) ![Node download](images/download_node.png)
@ -149,7 +151,7 @@ asabeneh $ node -v
v12.14.0 v12.14.0
``` ```
When making this tutorial I was using node version 12.14.0, but now the recommended version of node.js for download is 12.17.0. When making this tutorial I was using Node version 12.14.0, but now the recommended version of Node.js for download is v14.17.6, by the time you use this material you may have a higher Node.js version.
### Browser ### Browser
@ -157,7 +159,7 @@ There are many browsers out there. However, I strongly recommend Google Chrome.
#### Installing Google Chrome #### Installing Google Chrome
Install [google chrome](https://www.google.com/chrome/) if you do not have one yet. We can write small JavaScript code on the browser console, but we do not use the browser console to develop applications. Install [Google Chrome](https://www.google.com/chrome/) if you do not have one yet. We can write small JavaScript code on the browser console, but we do not use the browser console to develop applications.
![Google Chrome](images/google_chrome.png) ![Google Chrome](images/google_chrome.png)
@ -198,7 +200,7 @@ Ctl+Shift+I
##### Console.log ##### Console.log
To write our first JavaScript code, we used a built-in function **console.log()**. We passed an argument as input data, and the function displays the output. We passed 'Hello, World' as input data or argument in the console.log() function. To write our first JavaScript code, we used a built-in function **console.log()**. We passed an argument as input data, and the function displays the output. We passed `'Hello, World'` as input data or argument in the console.log() function.
```js ```js
console.log('Hello, World!') console.log('Hello, World!')
@ -206,7 +208,7 @@ console.log('Hello, World!')
##### Console.log with Multiple Arguments ##### Console.log with Multiple Arguments
The **conole.log()** function can take multiple parameters separated by comma. The syntax looks like as follows:**console.log(param1, param2, param3)** The **`console.log()`** function can take multiple parameters separated by commas. The syntax looks like as follows:**`console.log(param1, param2, param3)`**
![console log multiple arguments](./images/console_log_multipl_arguments.png) ![console log multiple arguments](./images/console_log_multipl_arguments.png)
@ -216,31 +218,35 @@ console.log('HAPPY', 'NEW', 'YEAR', 2020)
console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript') console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript')
``` ```
As you can see from the snippet code above, _console.log()_ can take multiple arguments. As you can see from the snippet code above, _`console.log()`_ can take multiple arguments.
Congratulations! You wrote your first JavaScript code using _console.log()_. Congratulations! You wrote your first JavaScript code using _`console.log()`_.
##### Comments ##### Comments
We add comments to our code. Comments are very important to make code more readable and to leave remarks in our code. JavaScript does not execute the comment part of our code.In JavaScript, any text line starting with // in JavaScript is a comment, and anything enclosed like this /\* \*/ is also a comment. We can add comments to our code. Comments are very important to make code more readable and to leave remarks in our code. JavaScript does not execute the comment part of our code. In JavaScript, any text line starting with // in JavaScript is a comment, and anything enclosed like this `//` is also a comment.
**Example: Single Line Comment** **Example: Single Line Comment**
```js
// This is the first comment // This is the first comment
// This is the second comment // This is the second comment
// I am a single line comment // I am a single line comment
```
**Example: Multiline Comment** **Example: Multiline Comment**
/_ ```js
/*
This is a multiline comment This is a multiline comment
Multiline comments can take multiple lines Multiline comments can take multiple lines
JavaScript is the language of the web JavaScript is the language of the web
_/ */
```
##### Syntax ##### Syntax
Programming languages are similar to human languages. English or many other language uses words, phrases, sentences,compound sentences and other more to convey a meaningful message. The English meaning of syntax is _the arrangement of words and phrases to create well-formed sentences in a language_. The technical definition of syntax is _the structure of statements in a computer language._ Programing languages have syntax. JavaScript is a programming language and like other programming languages it has its own syntax. If we do not write a syntax that JavaScript understands, it will raise different types of errors. We will explore different kinds of JavaScript errors later. For now, let us see syntax errors. Programming languages are similar to human languages. English or many other language uses words, phrases, sentences, compound sentences and other more to convey a meaningful message. The English meaning of syntax is _the arrangement of words and phrases to create well-formed sentences in a language_. The technical definition of syntax is the structure of statements in a computer language. Programming languages have syntax. JavaScript is a programming language and like other programming languages it has its own syntax. If we do not write a syntax that JavaScript understands, it will raise different types of errors. We will explore different kinds of JavaScript errors later. For now, let us see syntax errors.
![Error](images/raising_syntax_error.png) ![Error](images/raising_syntax_error.png)
@ -251,20 +257,20 @@ console.log('Hello, World!')
console.log('Hello, World!') console.log('Hello, World!')
``` ```
So far, we saw how to display text using the _console.log()_. If we are printing text or string using _console.log()_, the text has to be inside the single quotes, double quotes, or a backtick quotes. So far, we saw how to display text using the _`console.log()`_. If we are printing text or string using _`console.log()`_, the text has to be inside the single quotes, double quotes, or a backtick.
**Example:** **Example:**
```js ```js
console.log('Hello, World!') console.log('Hello, World!')
console.log('Hello, World!') console.log("Hello, World!")
console.log(`Hello, World!`) console.log(`Hello, World!`)
``` ```
#### Arithmetics #### Arithmetics
Now, let us practice more writing JavaScript codes using _console.log()_ on google chrome console for number data types. Now, let us practice more writing JavaScript codes using _`console.log()`_ on Google Chrome console for number data types.
In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations. In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations.
The console can directly take arguments without the **_console.log()_** function. However, it is included in this introduction because most of this challenge would be taking place in a text editor where the usage of the function would be mandatory. You can play around directly with instructions on the console. It is possible to write JavaScript code on Google Chrome console can directly without the **_`console.log()`_** function. However, it is included in this introduction because most of this challenge would be taking place in a text editor where the usage of the function would be mandatory. You can play around directly with instructions on the console.
![Arithmetic](images/arithmetic.png) ![Arithmetic](images/arithmetic.png)
@ -279,11 +285,11 @@ console.log(3 ** 2) // Exponentiation 3 ** 2 == 3 * 3
### Code Editor ### Code Editor
We can write our codes on the browser console, but it won't do for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 days JavaScript challenge, we will be using Visual Studio Code. We can write our codes on the browser console, but it won't be for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 days of JavaScript challenge, we will be using Visual Studio Code.
#### Installing Visual Studio Code #### Installing Visual Studio Code
Visual studio code is a very popular open-source text editor. I would recommend to [download Visual Studio Code](https://code.visualstudio.com/), but if you are in favor of other editors, feel free to follow with what you have. Visual Studio Code is a very popular open-source text editor. I would recommend to [download Visual Studio Code](https://code.visualstudio.com/), but if you are in favor of other editors, feel free to follow with what you have.
![Vscode](images/vscode.png) ![Vscode](images/vscode.png)
@ -320,11 +326,11 @@ The following sections show different ways of adding JavaScript code to your web
### Inline Script ### Inline Script
Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_index.html_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/). Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_`index.html`_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/).
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfScript:Inline Script</title> <title>30DaysOfScript:Inline Script</title>
</head> </head>
@ -334,16 +340,16 @@ Create a project folder on your desktop or in any location, name it 30DaysOfJS a
</html> </html>
``` ```
Now, you just wrote your first inline script. We can create a pop up alert message using the _alert()_ built-in function. Now, you just wrote your first inline script. We can create a pop up alert message using the _`alert()`_ built-in function.
### Internal Script ### Internal Script
The internal script can be written in the _head_ or the _body_, but it is preferred to put it on the body of the HTML document. The internal script can be written in the _`head`_ or the _`body`_, but it is preferred to put it on the body of the HTML document.
First, let us write on the head part of the page. First, let us write on the head part of the page.
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfScript:Internal Script</title> <title>30DaysOfScript:Internal Script</title>
<script> <script>
@ -354,11 +360,11 @@ First, let us write on the head part of the page.
</html> </html>
``` ```
This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the console.log() This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the `console.log()`.
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfScript:Internal Script</title> <title>30DaysOfScript:Internal Script</title>
</head> </head>
@ -371,14 +377,14 @@ This is how we write an internal script most of the time. Writing the JavaScript
</html> </html>
``` ```
Open the browser console to see the output from the console.log() Open the browser console to see the output from the `console.log()`.
![js code from vscode](./images/js_code_vscode.png) ![js code from vscode](./images/js_code_vscode.png)
### External Script ### External Script
Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body. Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body.
First, we should create an external JavaScript file with .js extension. All files ending with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body. First, we should create an external JavaScript file with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body.
```js ```js
console.log('Welcome to 30DaysOfJavaScript') console.log('Welcome to 30DaysOfJavaScript')
@ -388,7 +394,7 @@ External scripts in the _head_:
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:External script</title> <title>30DaysOfJavaScript:External script</title>
<script src="introduction.js"></script> <script src="introduction.js"></script>
@ -401,24 +407,24 @@ External scripts in the _body_:
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>30DaysOfJavaScript:External script</title> <title>30DaysOfJavaScript:External script</title>
</head> </head>
<body> <body>
//it could be in the header or in the body // Here is the recommended place <!-- JavaScript external link could be in the header or in the body -->
to put the external script <!-- Before the closing tag of the body is the recommended place to put the external JavaScript script -->
<script src="introduction.js"></script> <script src="introduction.js"></script>
</body> </body>
</html> </html>
``` ```
Open the browser console to see the output of the console.log() Open the browser console to see the output of the `console.log()`.
### Multiple External Scripts ### Multiple External Scripts
We can also link multiple external JavaScript files to a web page. We can also link multiple external JavaScript files to a web page.
Create a helloworld.js file inside the 30DaysOfJS folder and write the following code. Create a `helloworld.js` file inside the 30DaysOfJS folder and write the following code.
```js ```js
console.log('Hello, World!') console.log('Hello, World!')
@ -426,7 +432,7 @@ console.log('Hello, World!')
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html> <html lang="en">
<head> <head>
<title>Multiple External Scripts</title> <title>Multiple External Scripts</title>
</head> </head>
@ -443,7 +449,7 @@ _Your main.js file should be below all other scripts_. It is very important to r
## Introduction to Data types ## Introduction to Data types
In JavaScript and also other programming languages, there are different kinds of data types. The following are JavaScript primitive data types:_String, Number, Boolean, undefined, Null_, and _Symbol_. In JavaScript and also other programming languages, there are different types of data types. The following are JavaScript primitive data types: _String, Number, Boolean, undefined, Null_, and _Symbol_.
### Numbers ### Numbers
@ -457,28 +463,33 @@ In JavaScript and also other programming languages, there are different kinds of
### Strings ### Strings
A collection of one or more characters between two single quotes, double quotes, or backticks. A collection of one or more characters between two single quotes, double quotes, or backticks.
**Example:** **Example:**
```js ```js
'a'
'Asabeneh' 'Asabeneh'
"Asabeneh"
'Finland' 'Finland'
'JavaScript is a beautiful programming language' 'JavaScript is a beautiful programming language'
'I love teaching' 'I love teaching'
'I hope you are enjoying the first day'`We can also create a string using a backtick` 'I hope you are enjoying the first day'
;('A string could be just as small as one character as big as many pages') `We can also create a string using a backtick`
'A string could be just as small as one character or as big as many pages'
'Any data type under a single quote, double quote or backtick is a string'
``` ```
### Booleans ### Booleans
A boolean value is either True or False. Any comparisons return a boolean value, which is either true or false. A boolean value is either True or False. Any comparisons returns a boolean value, which is either true or false.
A boolean data type is either a true or false value. A boolean data type is either a true or false value.
**Example:** **Example:**
```js ```js
true // if the light on ,the value is true true // if the light is on, the value is true
false // if the light off, the value is false false // if the light is off, the value is false
``` ```
### Undefined ### Undefined
@ -487,7 +498,7 @@ In JavaScript, if we don't assign a value to a variable, the value is undefined.
```js ```js
let firstName let firstName
console.log(firstName) //not defined, because it is not assigned to a value yet console.log(firstName) // undefined, because it is not assigned to a value yet
``` ```
### Null ### Null
@ -539,7 +550,7 @@ Multiline commenting:
Variables are _containers_ of data. Variables are used to _store_ data in a memory location. When a variable is declared, a memory location is reserved. When a variable is assigned to a value (data), the memory space will be filled with that data. To declare a variable, we use _var_, _let_, or _const_ keywords. Variables are _containers_ of data. Variables are used to _store_ data in a memory location. When a variable is declared, a memory location is reserved. When a variable is assigned to a value (data), the memory space will be filled with that data. To declare a variable, we use _var_, _let_, or _const_ keywords.
For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do no change, and we can use _const_. We will not use var in this challenge and I don't recommend you to use it. It is error prone way of declaring variable it has lots of leak. We will talk more about var, let, and const in detail in other sections (scope). For now, the above explanation is enough. For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do not change, and we can use _const_. We will not use var in this challenge and I don't recommend you to use it. It is error prone way of declaring variable it has lots of leak. We will talk more about var, let, and const in detail in other sections (scope). For now, the above explanation is enough.
A valid JavaScript variable name must follow the following rules: A valid JavaScript variable name must follow the following rules:
@ -572,11 +583,11 @@ year2020
year_2020 year_2020
``` ```
The first and second variables on the list follows the camelCase convention of declaring in JavaScrip. In this material, we will use camelCase variables. The first and second variables on the list follows the camelCase convention of declaring in JavaScript. In this material, we will use camelCase variables(camelWithOneHump). We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about classes and objects in other section.
Example of invalid variables: Example of invalid variables:
```sh ```js
first-name first-name
1_num 1_num
num_#_1 num_#_1
@ -589,6 +600,8 @@ Let us declare variables with different data types. To declare a variable, we ne
let nameOfVariable = value let nameOfVariable = value
``` ```
The nameOfVriable is the name that stores different data of value. See below for detail examples.
**Examples of declared variables** **Examples of declared variables**
```js ```js
@ -604,16 +617,15 @@ console.log(firstName, lastName, country, city, age, isMarried)
``` ```
```sh ```sh
Asabeneh Yetayeh Finland Helsinki 100 True Asabeneh Yetayeh Finland Helsinki 100 true
``` ```
```js ```js
// Declaring variables with number values // Declaring variables with number values
let age = 100 // age in years let age = 100 // age in years
const gravity = 9.81 // earth gravity in m/s2 const gravity = 9.81 // earth gravity in m/s2
const boilingPoint = 100 // water boiling point, temperature in oC const boilingPoint = 100 // water boiling point, temperature in °C
const PI = 3.14 // geometrical constant const PI = 3.14 // geometrical constant
console.log(gravity, boilingPoint, PI) console.log(gravity, boilingPoint, PI)
``` ```
@ -622,10 +634,8 @@ console.log(gravity, boilingPoint, PI)
``` ```
```js ```js
// Variables can also be declaring in one line separated by comma // Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble
let name = 'Asabeneh', // name of a person let name = 'Asabeneh', job = 'teacher', live = 'Finland'
job = 'teacher',
live = 'Finland'
console.log(name, job, live) console.log(name, job, live)
``` ```

Loading…
Cancel
Save