Merge branch 'master' into master

pull/234/head
Sofía 4 years ago committed by GitHub
commit bfacc9df11
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

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

@ -19,30 +19,30 @@
![Thirty Days Of JavaScript](../images/banners/day_1_2.png)
- [📔 Day 2](#-day-2)
- [Data Types](#data-types)
- [Primitive Data Types](#primitive-data-types)
- [Non-Primitive Data Types](#non-primitive-data-types)
- [Numbers](#numbers)
- [Declaring Number Data Types](#declaring-number-data-types)
- [Math Object](#math-object)
- [Random Number Generator](#random-number-generator)
- [Strings](#strings)
- [String Concatenation](#string-concatenation)
- [Concatenating Using Addition Operator](#concatenating-using-addition-operator)
- [Long Literal Strings](#long-literal-strings)
- [Escape Sequences in Strings](#escape-sequences-in-strings)
- [Template Literals (Template Strings)](#template-literals-template-strings)
- [String Methods](#string-methods)
- [Checking Data Types and Casting](#checking-data-types-and-casting)
- [Checking Data Types](#checking-data-types)
- [Changing Data Type (Casting)](#changing-data-type-casting)
- [String to Int](#string-to-int)
- [String to Float](#string-to-float)
- [Float to Int](#float-to-int)
- [💻 Day 2: Exercises](#-day-2-exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Data Types](#data-types)
- [Primitive Data Types](#primitive-data-types)
- [Non-Primitive Data Types](#non-primitive-data-types)
- [Numbers](#numbers)
- [Declaring Number Data Types](#declaring-number-data-types)
- [Math Object](#math-object)
- [Random Number Generator](#random-number-generator)
- [Strings](#strings)
- [String Concatenation](#string-concatenation)
- [Concatenating Using Addition Operator](#concatenating-using-addition-operator)
- [Long Literal Strings](#long-literal-strings)
- [Escape Sequences in Strings](#escape-sequences-in-strings)
- [Template Literals (Template Strings)](#template-literals-template-strings)
- [String Methods](#string-methods)
- [Checking Data Types and Casting](#checking-data-types-and-casting)
- [Checking Data Types](#checking-data-types)
- [Changing Data Type (Casting)](#changing-data-type-casting)
- [String to Int](#string-to-int)
- [String to Float](#string-to-float)
- [Float to Int](#float-to-int)
- [💻 Day 2: Exercises](#-day-2-exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 2
@ -231,6 +231,10 @@ console.log(Math.E) // 2.718
console.log(Math.log(2)) // 0.6931471805599453
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
Math.sin(0)
Math.sin(60)
@ -876,7 +880,7 @@ console.log(numFloat) // 9.81
let num = '9.81'
let numFloat = +num
console.log(numInt) // 9.81
console.log(numFloat) // 9.81
```
#### Float to Int

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

@ -14,7 +14,7 @@ let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
// Let us extract numbers from text using regular expression. This is not regular expression section, no panic.
let txt = 'In 2019, I run 30 Days of Pyhton. Now, in 2020 I super exited to start this challenge'
let 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
// + means one or more digit numbers,
// 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.
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"]
let firstName = 'Asabeneh'

@ -18,38 +18,38 @@
![Thirty Days Of JavaScript](../images/banners/day_1_3.png)
- [📔 Day 3](#-day-3)
- [Booleans](#booleans)
- [Truthy values](#truthy-values)
- [Falsy values](#falsy-values)
- [Undefined](#undefined)
- [Null](#null)
- [Operators](#operators)
- [Assignment operators](#assignment-operators)
- [Arithmetic Operators](#arithmetic-operators)
- [Comparison Operators](#comparison-operators)
- [Logical Operators](#logical-operators)
- [Increment Operator](#increment-operator)
- [Decrement Operator](#decrement-operator)
- [Ternary Operators](#ternary-operators)
- [Operator Precendence](#operator-precendence)
- [Window Methods](#window-methods)
- [Window alert() method](#window-alert-method)
- [Window prompt() method](#window-prompt-method)
- [Window confirm() method](#window-confirm-method)
- [Date Object](#date-object)
- [Creating a time object](#creating-a-time-object)
- [Getting full year](#getting-full-year)
- [Getting month](#getting-month)
- [Getting date](#getting-date)
- [Getting day](#getting-day)
- [Getting hours](#getting-hours)
- [Getting minutes](#getting-minutes)
- [Getting seconds](#getting-seconds)
- [Getting time](#getting-time)
- [💻 Day 3: Exercises](#-day-3-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Booleans](#booleans)
- [Truthy values](#truthy-values)
- [Falsy values](#falsy-values)
- [Undefined](#undefined)
- [Null](#null)
- [Operators](#operators)
- [Assignment operators](#assignment-operators)
- [Arithmetic Operators](#arithmetic-operators)
- [Comparison Operators](#comparison-operators)
- [Logical Operators](#logical-operators)
- [Increment Operator](#increment-operator)
- [Decrement Operator](#decrement-operator)
- [Ternary Operators](#ternary-operators)
- [Operator Precedence](#operator-precedence)
- [Window Methods](#window-methods)
- [Window alert() method](#window-alert-method)
- [Window prompt() method](#window-prompt-method)
- [Window confirm() method](#window-confirm-method)
- [Date Object](#date-object)
- [Creating a time object](#creating-a-time-object)
- [Getting full year](#getting-full-year)
- [Getting month](#getting-month)
- [Getting date](#getting-date)
- [Getting day](#getting-day)
- [Getting hours](#getting-hours)
- [Getting minutes](#getting-minutes)
- [Getting seconds](#getting-seconds)
- [Getting time](#getting-time)
- [💻 Day 3: Exercises](#-day-3-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 3
@ -218,7 +218,7 @@ console.log('python'.length > 'dragon'.length) // false
```
Try to understand the above comparisons with some logic. Remembering without any logic might be difficult.
JavaScript is some how a wired kind of programming language. JavaScript code run and give you a result but unless you are good at it may not be the desired result.
JavaScript is somehow a wired kind of programming language. JavaScript code run and give you a result but unless you are good at it may not be the desired result.
As rule of thumb, if a value is not true with == it will not be equal with ===. Using === is safer than using ==. The following [link](https://dorey.github.io/JavaScript-Equality-Table/) has an exhaustive list of comparison of data types.
@ -254,7 +254,7 @@ let isMarried = !false // true
### 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
@ -276,7 +276,7 @@ We use most of the time post-increment. At least you should remember how to use
### 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
@ -333,9 +333,9 @@ number > 0
-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
@ -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 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. 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. 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?
```sh

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

@ -18,16 +18,16 @@
![Thirty Days Of JavaScript](../images/banners/day_1_4.png)
- [📔 Day 4](#-day-4)
- [Conditionals](#conditionals)
- [If](#if)
- [If Else](#if-else)
- [If Else if Else](#if-else-if-else)
- [Switch](#switch)
- [Ternary Operators](#ternary-operators)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Conditionals](#conditionals)
- [If](#if)
- [If Else](#if-else)
- [If Else if Else](#if--else-if-else)
- [Switch](#switch)
- [Ternary Operators](#ternary-operators)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 4
@ -189,7 +189,8 @@ switch(caseValue){
// code
break
case 3:
// code
// code
break
default:
// code
}
@ -279,7 +280,7 @@ isRaining
### 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
Enter your age: 30

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

@ -18,35 +18,35 @@
![Day 5](../images/banners/day_1_5.png)
- [📔 Day 5](#-day-5)
- [Arrays](#arrays)
- [How to create an empty array](#how-to-create-an-empty-array)
- [How to create an array with values](#how-to-create-an-array-with-values)
- [Creating an array using split](#creating-an-array-using-split)
- [Accessing array items using index](#accessing-array-items-using-index)
- [Modifying array element](#modifying-array-element)
- [Methods to manipulate array](#methods-to-manipulate-array)
- [Array Constructor](#array-constructor)
- [Creating static values with fill](#creating-static-values-with-fill)
- [Concatenating array using concat](#concatenating-array-using-concat)
- [Getting array length](#getting-array-length)
- [Getting index an element in arr array](#getting-index-an-element-in-arr-array)
- [Getting last index of an element in array](#getting-last-index-of-an-element-in-array)
- [Checking array](#checking-array)
- [Converting array to string](#converting-array-to-string)
- [Joining array elements](#joining-array-elements)
- [Slice array elements](#slice-array-elements)
- [Splice method in array](#splice-method-in-array)
- [Adding item to an array using push](#adding-item-to-an-array-using-push)
- [Removing the end element using pop](#removing-the-end-element-using-pop)
- [Removing an element from the beginning](#removing-an-element-from-the-beginning)
- [Add an element from the beginning](#add-an-element-from-the-beginning)
- [Reversing array order](#reversing-array-order)
- [Sorting elements in array](#sorting-elements-in-array)
- [Array of arrays](#array-of-arrays)
- [💻 Exercise](#-exercise)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
- [Arrays](#arrays)
- [How to create an empty array](#how-to-create-an-empty-array)
- [How to create an array with values](#how-to-create-an-array-with-values)
- [Creating an array using split](#creating-an-array-using-split)
- [Accessing array items using index](#accessing-array-items-using-index)
- [Modifying array element](#modifying-array-element)
- [Methods to manipulate array](#methods-to-manipulate-array)
- [Array Constructor](#array-constructor)
- [Creating static values with fill](#creating-static-values-with-fill)
- [Concatenating array using concat](#concatenating-array-using-concat)
- [Getting array length](#getting-array-length)
- [Getting index an element in arr array](#getting-index-an-element-in-arr-array)
- [Getting last index of an element in array](#getting-last-index-of-an-element-in-array)
- [Checking array](#checking-array)
- [Converting array to string](#converting-array-to-string)
- [Joining array elements](#joining-array-elements)
- [Slice array elements](#slice-array-elements)
- [Splice method in array](#splice-method-in-array)
- [Adding item to an array using push](#adding-item-to-an-array-using-push)
- [Removing the end element using pop](#removing-the-end-element-using-pop)
- [Removing an element from the beginning](#removing-an-element-from-the-beginning)
- [Add an element from the beginning](#add-an-element-from-the-beginning)
- [Reversing array order](#reversing-array-order)
- [Sorting elements in array](#sorting-elements-in-array)
- [Array of arrays](#array-of-arrays)
- [💻 Exercise](#-exercise)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
# 📔 Day 5
@ -390,22 +390,22 @@ Check an element if it exist in an array.
const fruits = ['banana', 'orange', 'mango', 'lemon']
let index = fruits.indexOf('banana') // 0
if(index != -1){
console.log('This fruit does exist in the array')
if(index === -1){
console.log('This fruit does not exist in the array')
} else {
console.log('This fruit does not exist in the array')
console.log('This fruit does exist in the array')
}
// This fruit does exist in the array
// we can use also ternary here
index != -1 ? console.log('This fruit does exist in the array'): console.log('This fruit does not exist in the array')
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 indexOfAvocado = fruits.indexOf('avocado') // -1, if the element not found index is -1
if(indexOfAvocado!= -1){
console.log('This fruit does exist in the array')
if(indexOfAvocado === -1){
console.log('This fruit does not exist in the array')
} else {
console.log('This fruit does not exist in the array')
console.log('This fruit does exist in the array')
}
// This fruit does not exist in the array
```

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:05 Day </title>
<title>30DaysOfJavaScript:05 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:05 Day</h1>
<h2>Arrays</h2>
<script src="./data/countries.js"></script>
<script src="./scripts/main.js"></script>
<h1>30DaysOfJavaScript:05 Day</h1>
<h2>Arrays</h2>
<script src="./data/countries.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -18,17 +18,17 @@
![Day 5](../images/banners/day_1_6.png)
- [📔 Day 6](#-day-6)
- [Loops](#loops)
- [for Loop](#for-loop)
- [while loop](#while-loop)
- [do while loop](#do-while-loop)
- [for of loop](#for-of-loop)
- [break](#break)
- [continue](#continue)
- [💻 Exercises:Day 6](#-exercisesday-6)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Loops](#loops)
- [for Loop](#for-loop)
- [while loop](#while-loop)
- [do while loop](#do-while-loop)
- [for of loop](#for-of-loop)
- [break](#break)
- [continue](#continue)
- [💻 Exercises:Day 6](#-exercisesday-6)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 6
@ -178,7 +178,9 @@ for (const num of numbers) {
// adding all the numbers in the array
let sum = 0
for (const num of numbers) {
sum = sum + num // can be also shorten like this, sum += num
sum = sum + num
// can be also shorten like this, sum += num
// after this we will use the shorter synthax(+=, -=, *=, /= etc)
}
console.log(sum) // 15

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

@ -18,26 +18,26 @@
![Thirty Days Of JavaScript](../images/banners/day_1_7.png)
- [📔 Day 7](#-day-7)
- [Functions](#functions)
- [Function Declaration](#function-declaration)
- [Function without a parameter and return](#function-without-a-parameter-and-return)
- [Function returning value](#function-returning-value)
- [Function with a parameter](#function-with-a-parameter)
- [Function with two parameters](#function-with-two-parameters)
- [Function with many parameters](#function-with-many-parameters)
- [Function with unlimited number of parameters](#function-with-unlimited-number-of-parameters)
- [Unlimited number of parameters in regular function](#unlimited-number-of-parameters-in-regular-function)
- [Unlimited number of parameters in arrow function](#unlimited-number-of-parameters-in-arrow-function)
- [Anonymous Function](#anonymous-function)
- [Expression Function](#expression-function)
- [Self Invoking Functions](#self-invoking-functions)
- [Arrow Function](#arrow-function)
- [Function with default parameters](#function-with-default-parameters)
- [Function declaration versus Arrow function](#function-declaration-versus-arrow-function)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Functions](#functions)
- [Function Declaration](#function-declaration)
- [Function without a parameter and return](#function-without-a-parameter-and-return)
- [Function returning value](#function-returning-value)
- [Function with a parameter](#function-with-a-parameter)
- [Function with two parameters](#function-with-two-parameters)
- [Function with many parameters](#function-with-many-parameters)
- [Function with unlimited number of parameters](#function-with-unlimited-number-of-parameters)
- [Unlimited number of parameters in regular function](#unlimited-number-of-parameters-in-regular-function)
- [Unlimited number of parameters in arrow function](#unlimited-number-of-parameters-in-arrow-function)
- [Anonymous Function](#anonymous-function)
- [Expression Function](#expression-function)
- [Self Invoking Functions](#self-invoking-functions)
- [Arrow Function](#arrow-function)
- [Function with default parameters](#function-with-default-parameters)
- [Function declaration versus Arrow function](#function-declaration-versus-arrow-function)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 7
@ -239,7 +239,7 @@ function sumAllNums() {
console.log(arguments)
}
sumAllNums(1, 2, 3, 4))
sumAllNums(1, 2, 3, 4)
// 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) => {
// 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)
}
@ -506,8 +506,7 @@ 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.
## 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/)
## 💻 Exercises
@ -524,7 +523,7 @@ Now it is time to express your thoughts about the Author and 30DaysOfJavaScript.
9. Density of a substance is calculated as follows:_density= mass/volume_. Write a function which calculates _density_.
10. Speed is calculated by dividing the total distance covered by a moving object divided by the total amount of time taken. Write a function which calculates a speed of a moving object, _speed_.
11. Weight of a substance is calculated as follows: _weight = mass x gravity_. Write a function which calculates _weight_.
12. Temperature in oC can be converted to oF using this formula: _oF = (oC x 9/5) + 32_. Write a function which convert oC to oF _convertCelciusToFahrenheit_.
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.
- The same groups apply to both men and women.

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

@ -18,50 +18,49 @@
![Thirty Days Of JavaScript](../images/banners/day_1_8.png)
- [📔 Day 8](#-day-8)
- [Scope](#scope)
- [Window Scope](#window-scope)
- [Global scope](#global-scope)
- [Local scope](#local-scope)
- [📔 Object](#-object)
- [Creating an empty object](#creating-an-empty-object)
- [Creating an objecting with values](#creating-an-objecting-with-values)
- [Getting values from an object](#getting-values-from-an-object)
- [Creating object methods](#creating-object-methods)
- [Setting new key for an object](#setting-new-key-for-an-object)
- [Object Methods](#object-methods)
- [Getting object keys using Object.keys()](#getting-object-keys-using-objectkeys)
- [Getting object values using Object.values()](#getting-object-values-using-objectvalues)
- [Getting object keys and values using Object.entries()](#getting-object-keys-and-values-using-objectentries)
- [Checking properties using hasOwnProperty()](#checking-properties-using-hasownproperty)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Scope](#scope)
- [Window Global Object](#window-global-object)
- [Global scope](#global-scope)
- [Local scope](#local-scope)
- [📔 Object](#-object)
- [Creating an empty object](#creating-an-empty-object)
- [Creating an objecting with values](#creating-an-objecting-with-values)
- [Getting values from an object](#getting-values-from-an-object)
- [Creating object methods](#creating-object-methods)
- [Setting new key for an object](#setting-new-key-for-an-object)
- [Object Methods](#object-methods)
- [Getting object keys using Object.keys()](#getting-object-keys-using-objectkeys)
- [Getting object values using Object.values()](#getting-object-values-using-objectvalues)
- [Getting object keys and values using Object.entries()](#getting-object-keys-and-values-using-objectentries)
- [Checking properties using hasOwnProperty()](#checking-properties-using-hasownproperty)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 8
## Scope
Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word _var_, _let_ and _const_. A variable can declared at different scope. In this section we will see the scope, scope of variables when we use var or let.
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:
- Window
- Global
- Local
Variable can be declared globally or locally or window scope. We will see both global and local scope.
Anything declared without let, var or const is scoped at window level.
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 global level.
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.
```js
//scope.js
a = 'JavaScript' // is a window scope this found anywhere
b = 10 // this is a window scope variable
a = 'JavaScript' // declaring a variable without let or const make it available in window object and this found anywhere
b = 10 // this is a global scope variable and found in the window object
function letsLearnScope() {
console.log(a, b)
if (true) {
@ -96,13 +95,18 @@ console.log(a, b) // JavaScript 10, accessible
A variable declared as local can be accessed only in certain block code.
- Block Scope
- Function Scope
```js
//scope.js
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
let b = 10 // is a global scope it will be found anywhere in this file
// Function scope
function letsLearnScope() {
console.log(a, b) // JavaScript 10, accessible
let value = false
// block scope
if (true) {
// we can access from the function and outside the function but
// variables declared inside the if will not be accessed outside the if block
@ -111,7 +115,7 @@ function letsLearnScope() {
let c = 30
let d = 40
value = !value
console.log(a, b, c) // Python 20 30
console.log(a, b, c, value) // Python 20 30 true
}
// we can not access c because c's scope is only the if block
console.log(a, b, value) // JavaScript 10 true
@ -138,9 +142,9 @@ if (true){
console.log(gravity) // 9.81
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
```
@ -163,13 +167,13 @@ if (true){
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
for(let i = 0; i < 3; i++){
console.log(i) // 1, 2, 3
console.log(i) // 0, 1, 2
}
// 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
@ -252,14 +256,14 @@ const person = {
console.log(person.firstName)
console.log(person.lastName)
console.log(person.age)
console.log(person.location)
console.log(person.location) // undefined
// value can be accessed using square bracket and key name
console.log(person['firstName'])
console.log(person['lastName'])
console.log(person['age'])
console.log(person['age'])
console.log(person['location'])
console.log(person['location']) // undefined
// for instance to access the phone number we only use the square bracket method
console.log(person['phone number'])

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

@ -19,29 +19,29 @@
![Day 5](../images/banners/day_1_9.png)
- [Day 9](#day-9)
- [Higher Order Function](#higher-order-function)
- [Callback](#callback)
- [Returning function](#returning-function)
- [setting time](#setting-time)
- [setInterval](#setinterval)
- [setTimeout](#settimeout)
- [Functional Programming](#functional-programming)
- [forEach](#foreach)
- [map](#map)
- [filter](#filter)
- [reduce](#reduce)
- [every](#every)
- [find](#find)
- [findIndex](#findindex)
- [some](#some)
- [sort](#sort)
- [Sorting string values](#sorting-string-values)
- [Sorting Numeric values](#sorting-numeric-values)
- [Sorting Object Arrays](#sorting-object-arrays)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Higher Order Function](#higher-order-function)
- [Callback](#callback)
- [Returning function](#returning-function)
- [Setting time](#setting-time)
- [Setting Interval using a setInterval function](#setting-interval-using-a-setinterval-function)
- [Setting a time using a setTimeout](#setting-a-time-using-a-settimeout)
- [Functional Programming](#functional-programming)
- [forEach](#foreach)
- [map](#map)
- [filter](#filter)
- [reduce](#reduce)
- [every](#every)
- [find](#find)
- [findIndex](#findindex)
- [some](#some)
- [sort](#sort)
- [Sorting string values](#sorting-string-values)
- [Sorting Numeric values](#sorting-numeric-values)
- [Sorting Object Arrays](#sorting-object-arrays)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 9
@ -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.
```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) => {
return n ** 2
}
// function take other function as a callback
// function that takes other function as a callback
function cube(callback, n) {
return callback(n) * n
}
@ -71,7 +71,6 @@ console.log(cube(callback, 3))
Higher order functions return function as a value
```js
// Higher order function returning an other function
const higherOrder = n => {
@ -90,7 +89,6 @@ Let us see were we use call back functions. For instance the _forEach_ method us
```js
const numbers = [1, 2, 3, 4]
const sumArray = arr => {
let sum = 0
const callback = function(element) {
@ -134,7 +132,7 @@ In JavaScript we can execute some activities in a certain interval of time or we
- setInterval
- setTimeout
#### Setting Interaval using a setInterval function
#### 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.
@ -354,8 +352,8 @@ const scores = [
{ name: 'John', score: 100 },
]
const scoresGreaterEight = scores.filter((score) => score.score > 80)
console.log(scoresGreaterEight)
const scoresGreaterEighty = scores.filter((score) => score.score > 80)
console.log(scoresGreaterEighty)
```
```sh
@ -392,7 +390,7 @@ _every_: Check if all the elements are similar in one aspect. It returns boolean
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const areAllStr = names.every((name) => typeof name === 'string') // Are all strings?
console.log(arrAllStr)
console.log(areAllStr)
```
```sh
@ -573,7 +571,7 @@ const products = [
```
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.
4. Use **_forEach_** to console.log each name in the names array.
5. Use **_forEach_** to console.log each number in the numbers array.

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

@ -19,26 +19,26 @@
![Day 10](../images/banners/day_1_10.png)
- [Day 10](#day-10)
- [Set](#set)
- [Creating an empty set](#creating-an-empty-set)
- [Creating set from array](#creating-set-from-array)
- [Adding an element to a set](#adding-an-element-to-a-set)
- [Deleting an element a set](#deleting-an-element-a-set)
- [Checking an element in the set](#checking-an-element-in-the-set)
- [Clearing the set](#clearing-the-set)
- [Union of sets](#union-of-sets)
- [Intersection of sets](#intersection-of-sets)
- [Difference of sets](#difference-of-sets)
- [Map](#map)
- [Creating an empty Map](#creating-an-empty-map)
- [Creating an Map from array](#creating-an-map-from-array)
- [Adding values to the Map](#adding-values-to-the-map)
- [Getting a value from Map](#getting-a-value-from-map)
- [Checking key in Map](#checking-key-in-map)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises:Level 2](#exerciseslevel-2)
- [Exercises:Level 3](#exerciseslevel-3)
- [Set](#set)
- [Creating an empty set](#creating-an-empty-set)
- [Creating set from array](#creating-set-from-array)
- [Adding an element to a set](#adding-an-element-to-a-set)
- [Deleting an element a set](#deleting-an-element-a-set)
- [Checking an element in the set](#checking-an-element-in-the-set)
- [Clearing the set](#clearing-the-set)
- [Union of sets](#union-of-sets)
- [Intersection of sets](#intersection-of-sets)
- [Difference of sets](#difference-of-sets)
- [Map](#map)
- [Creating an empty Map](#creating-an-empty-map)
- [Creating an Map from array](#creating-an-map-from-array)
- [Adding values to the Map](#adding-values-to-the-map)
- [Getting a value from Map](#getting-a-value-from-map)
- [Checking key in Map](#checking-key-in-map)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises:Level 2](#exerciseslevel-2)
- [Exercises:Level 3](#exerciseslevel-3)
# Day 10
@ -71,8 +71,8 @@ const languages = [
'French',
]
const setOfLangauges = new Set(languages)
console.log(setOfLangauges)
const setOfLanguages = new Set(languages)
console.log(setOfLanguages)
```
```sh
@ -92,9 +92,9 @@ const languages = [
'French',
]
const setOfLangauges = new Set(languages)
const setOfLanguages = new Set(languages)
for (const language of setOfLangauges) {
for (const language of setOfLanguages) {
console.log(language)
}
```

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

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:11 Day </title>
<title>30DaysOfJavaScript:11 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -18,29 +18,29 @@
![Thirty Days Of JavaScript](../images/banners/day_1_12.png)
- [📘 Day 12](#-day-12)
- [Regular Expressions](#regular-expressions)
- [RegExp parameters](#regexp-parameters)
- [Pattern](#pattern)
- [Flags](#flags)
- [Creating a pattern with RegExp Constructor](#creating-a-pattern-with-regexp-constructor)
- [Creating a pattern without RegExp Constructor](#creating-a-pattern-without-regexp-constructor)
- [RegExpp Object Methods](#regexpp-object-methods)
- [Testing for a match](#testing-for-a-match)
- [Array containing all of the match](#array-containing-all-of-the-match)
- [Replacing a substring](#replacing-a-substring)
- [Square Bracket](#square-bracket)
- [Escape character(\\) in RegExp](#escape-character-in-regexp)
- [One or more times(+)](#one-or-more-times)
- [Period(.)](#period)
- [Zero or more times(*)](#zero-or-more-times)
- [Zero or one times(?)](#zero-or-one-times)
- [Quantifier in RegExp](#quantifier-in-regexp)
- [Cart ^](#cart-)
- [Exact match](#exact-match)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Regular Expressions](#regular-expressions)
- [RegExp parameters](#regexp-parameters)
- [Pattern](#pattern)
- [Flags](#flags)
- [Creating a pattern with RegExp Constructor](#creating-a-pattern-with-regexp-constructor)
- [Creating a pattern without RegExp Constructor](#creating-a-pattern-without-regexp-constructor)
- [RegExpp Object Methods](#regexpp-object-methods)
- [Testing for a match](#testing-for--a-match)
- [Array containing all of the match](#array-containing-all-of-the-match)
- [Replacing a substring](#replacing-a-substring)
- [Square Bracket](#square-bracket)
- [Escape character(\\) in RegExp](#escape-character-in-regexp)
- [One or more times(+)](#one-or-more-times)
- [Period(.)](#period)
- [Zero or more times(*)](#zero-or-more-times)
- [Zero or one times(?)](#zero-or-one-times)
- [Quantifier in RegExp](#quantifier-in-regexp)
- [Cart ^](#cart-)
- [Exact match](#exact-match)
- [💻 Exercises](#-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📘 Day 12
@ -503,22 +503,19 @@ distance = 12
```js
sentence = `%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?`
console.log(cleanText(sentence))
console.log(cleanText(sentence))
```
```sh
I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher
```
1. Write a function which find the most frequent words. After cleaning, count three most frequent words in the string.
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))
[{word:'I', count:3}, {word:'teaching', count:2}, {word:'teacher', count:2}]
```
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 11](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | [Day 13>>](../13_Day_Console_object_methods/13_day_console_object_methods.md)
[<< 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,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:11 Day </title>
<title>30DaysOfJavaScript:11 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:13 Day </title>
<title>30DaysOfJavaScript:13 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:13 Day</h1>
<h2>Console Object Methods</h2>
<h1>30DaysOfJavaScript:13 Day</h1>
<h2>Console Object Methods</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -19,12 +19,12 @@
![Thirty Days Of JavaScript](../images/banners/day_1_14.png)
- [Day 14](#day-14)
- [Error Handling](#error-handling)
- [Error Types](#error-types)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises:Level](#exerciseslevel)
- [Error Handling](#error-handling)
- [Error Types](#error-types)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises:Level](#exerciseslevel)
# Day 14
@ -113,7 +113,7 @@ throw new Error('Required') // generates an error object with the message of Req
```
```js
const throwErroExampleFun = () => {
const throwErrorExampleFun = () => {
let message
let x = prompt('Enter a number: ')
try {
@ -126,7 +126,7 @@ const throwErroExampleFun = () => {
console.log(err)
}
}
throwErroExampleFun()
throwErrorExampleFun()
```
### Error Types

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:12 Day </title>
<title>30DaysOfJavaScript:12 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:14 Day</h1>
<h2>DOM</h2>
<h1>30DaysOfJavaScript:14 Day</h1>
<h2>DOM</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -19,22 +19,22 @@
![Thirty Days Of JavaScript](../images/banners/day_1_15.png)
- [Day 15](#day-15)
- [Classes](#classes)
- [Defining a classes](#defining-a-classes)
- [Class Instantiation](#class-instantiation)
- [Class Constructor](#class-constructor)
- [Default values with constructor](#default-values-with-constructor)
- [Class methods](#class-methods)
- [Properties with initial value](#properties-with-initial-value)
- [getter](#getter)
- [setter](#setter)
- [Static method](#static-method)
- [Inheritance](#inheritance)
- [Overriding methods](#overriding-methods)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Exercises Level 3](#exercises-level-3)
- [Classes](#classes)
- [Defining a classes](#defining-a-classes)
- [Class Instantiation](#class-instantiation)
- [Class Constructor](#class-constructor)
- [Default values with constructor](#default-values-with-constructor)
- [Class methods](#class-methods)
- [Properties with initial value](#properties-with-initial-value)
- [getter](#getter)
- [setter](#setter)
- [Static method](#static-method)
- [Inheritance](#inheritance)
- [Overriding methods](#overriding-methods)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Exercises Level 3](#exercises-level-3)
# Day 15
@ -111,7 +111,7 @@ console.log(person)
```
```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.
@ -305,7 +305,7 @@ class Person {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getscore() {
get getScore() {
return this.score
}
get getSkills() {

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

@ -19,16 +19,16 @@
![Thirty Days Of JavaScript](../images/banners/day_1_16.png)
- [Day 16](#day-16)
- [JSON](#json)
- [Converting JSON to JavaScript Object](#converting-json-to-javascript-object)
- [JSON.parse()](#jsonparse)
- [Using a reviver function with JSON.parse()](#using-a-reviver-function-with-jsonparse)
- [Converting Object to JSON](#converting-object-to-json)
- [Using a Filter Array with JSON.stringify](#using-a-filter-array-with-jsonstringify)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Exercises Level 3](#exercises-level-3)
- [JSON](#json)
- [Converting JSON to JavaScript Object](#converting-json-to-javascript-object)
- [JSON.parse()](#jsonparse)
- [Using a reviver function with JSON.parse()](#using-a-reviver-function-with-jsonparse)
- [Converting Object to JSON](#converting-object-to-json)
- [Using a Filter Array with JSON.stringify](#using-a-filter-array-with-jsonstringify)
- [Exercises](#exercises)
- [Exercises Level 1](#exercises-level-1)
- [Exercises Level 2](#exercises-level-2)
- [Exercises Level 3](#exercises-level-3)
# Day 16
@ -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.
@ -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 or text , the data
// reviver is an optional callback function
/* JSON.parse(json, (key, value) => {
})
*/
```
```js
@ -440,7 +444,7 @@ const user = {
country: 'Finland',
city: 'Helsinki',
email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Pyhton'],
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Python'],
age: 250,
isLoggedIn: false,
points: 30
@ -576,11 +580,8 @@ const txt = `{
### Exercises Level 1
1. Change skills array to JSON using JSON.stringify()
1. Stringify the age variable
1. Stringify the isMarried variable
1. Stringify the student object
### Exercises Level 2
@ -590,7 +591,7 @@ const txt = `{
### Exercises Level 3
1. Parse the *txt* JSON to object.
2. Find the the user who has many skills from the variable stored in *txt*.
2. Find the user who has many skills from the variable stored in *txt*.
🎉 CONGRATULATIONS ! 🎉

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:16 Day </title>
<title>30DaysOfJavaScript:16 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:16 Day</h1>
<h2>JSON</h2>
<h1>30DaysOfJavaScript:16 Day</h1>
<h2>JSON</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

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

@ -19,18 +19,18 @@
![Thirty Days Of JavaScript](../images/banners/day_1_17.png)
- [Day 17](#day-17)
- [HTML5 Web Storage](#html5-web-storage)
- [sessionStorage](#sessionstorage)
- [localStorage](#localstorage)
- [Use case of Web Storages](#use-case-of-web-storages)
- [HTML5 Web Storage Objects](#html5-web-storage-objects)
- [Setting item to the localStorage](#setting-item-to-the-localstorage)
- [Getting item from localStorage](#getting-item-from-localstorage)
- [Clearing the localStorage](#clearing-the-localstorage)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [HTML5 Web Storage](#html5-web-storage)
- [sessionStorage](#sessionstorage)
- [localStorage](#localstorage)
- [Use case of Web Storages](#use-case-of-web-storages)
- [HTML5 Web Storage Objects](#html5-web-storage-objects)
- [Setting item to the localStorage](#setting-item-to-the-localstorage)
- [Getting item from localStorage](#getting-item-from-localstorage)
- [Clearing the localStorage](#clearing-the-localstorage)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 17
@ -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.
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
@ -90,7 +90,7 @@ Web Storage objects:
- _localStorage_ - to display the localStorage object
- _localStorage.clear()_ - to remove everything in the local storage
- _localStorage.setItem()_ - to storage data in the localStorage. It takes a key and a value parameters.
- _localStorage.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.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.

@ -19,15 +19,15 @@
![Thirty Days Of JavaScript](../images/banners/day_1_18.png)
- [Day 18](#day-18)
- [Promise](#promise)
- [Callbacks](#callbacks)
- [Promise constructor](#promise-constructor)
- [Fetch API](#fetch-api)
- [Async and Await](#async-and-await)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Promise](#promise)
- [Callbacks](#callbacks)
- [Promise constructor](#promise-constructor)
- [Fetch API](#fetch-api)
- [Async and Await](#async-and-await)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 18
@ -105,7 +105,7 @@ doSomething((err, result) => {
### 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
// syntax
@ -147,7 +147,7 @@ Let us another example when the promise is settled with reject.
const doPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
if (skills.icludes('Node')) {
if (skills.includes('Node')) {
resolve('fullstack developer')
} else {
reject('Something wrong has happened')
@ -244,7 +244,7 @@ console.log('===== async and await')
fetchData()
```
🌕 You are real and you kept your promise and your reached to day 18. Keep your promise and settle the challenge with resolve. You are 18 steps a head to your way to greatness. Now do some exercises for your brain and for your muscle.
🌕 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

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:18 Day </title>
<title>30DaysOfJavaScript:18 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:18 Day</h1>
<h2>Promises</h2>
<h1>30DaysOfJavaScript:18 Day</h1>
<h2>Promises</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -14,15 +14,15 @@
</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)
- [Day 19](#day-19)
- [Closure](#closure)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Closure](#closure)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 19
@ -80,7 +80,7 @@ console.log(innerFuncs.minusOne)
```sh
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.
@ -101,4 +101,4 @@ console.log(innerFuncs.minusOne)
🎉 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,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:19 Day </title>
<title>30DaysOfJavaScript:19 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:19 Day</h1>
<h2>Writing Clean Code</h2>
<h1>30DaysOfJavaScript:19 Day</h1>
<h2>Writing Clean Code</h2>
<script src="./scripts/main.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:20 Day </title>
<title>30DaysOfJavaScript:20 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:20 Day</h1>
<h2>Writing clean code</h2>
<h1>30DaysOfJavaScript:20 Day</h1>
<h2>Writing clean code</h2>
<script src="./scripts/main.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -18,21 +18,21 @@
![Thirty Days Of JavaScript](../images/banners/day_1_20.png)
- [Day 20](#day-20)
- [Writing clean code](#writing-clean-code)
- [JavaScript Style Guide](#javascript-style-guide)
- [Why we need style guide](#why-we-need-style-guide)
- [Airbnb JavaScript Style Guide](#airbnb-javascript-style-guide)
- [Standard JavaScript Style Guide](#standard-javascript-style-guide)
- [Google JavaScript Style Guide](#google-javascript-style-guide)
- [JavaScript Coding Conventions](#javascript-coding-conventions)
- [Conventions use in 30DaysOfJavaScript](#conventions-use-in-30daysofjavascript)
- [Variables](#variables)
- [Arrays](#arrays)
- [Functions](#functions)
- [Loops](#loops)
- [Objects](#objects)
- [Conditional](#conditional)
- [Classes](#classes)
- [Writing clean code](#writing-clean-code)
- [JavaScript Style Guide](#javascript-style-guide)
- [Why we need style guide](#why-we-need-style-guide)
- [Airbnb JavaScript Style Guide](#airbnb-javascript-style-guide)
- [Standard JavaScript Style Guide](#standard-javascript-style-guide)
- [Google JavaScript Style Guide](#google-javascript-style-guide)
- [JavaScript Coding Conventions](#javascript-coding-conventions)
- [Conventions use in 30DaysOfJavaScript](#conventions-use-in-30daysofjavascript)
- [Variables](#variables)
- [Arrays](#arrays)
- [Functions](#functions)
- [Loops](#loops)
- [Objects](#objects)
- [Conditional](#conditional)
- [Classes](#classes)
# Day 20
@ -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
```js
// function which prints full name of a person
// function which return full name of a person
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
// 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
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.
@ -202,7 +204,7 @@ for(let i = 0; i < len; i++){
// iterating an array using for of
for( const name of names) {
console.log(name.toUpperCasee())
console.log(name.toUpperCase())
}
// iterating array using forEach
@ -218,7 +220,7 @@ const person = {
skills: ['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js'],
isMarried: true
}
for(const key in user) {
for(const key in person) {
console.log(key)
}
@ -236,7 +238,7 @@ const person = {
age: 250,
country: 'Finland',
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
}
// iterating through object keys
@ -244,7 +246,6 @@ for(const key in person) {
console.log(key, person[key])
}
```
#### Conditional

@ -19,31 +19,31 @@
![Thirty Days Of JavaScript](../images/banners/day_1_21.png)
- [Day 21](#day-21)
- [Document Object Model (DOM) - Day 1](#document-object-model-dom---day-1)
- [Getting Element](#getting-element)
- [Getting elements by tag name](#getting-elements-by-tag-name)
- [Getting elements by class name](#getting-elements-by-class-name)
- [Getting an element by id](#getting-an-element-by-id)
- [Getting elements by using querySelector methods](#getting-elements-by-using-queryselector-methods)
- [Adding attribute](#adding-attribute)
- [Adding attribute using setAttribute](#adding-attribute-using-setattribute)
- [Adding attribute without setAttribute](#adding-attribute-without-setattribute)
- [Adding class using classList](#adding-class-using-classlist)
- [Removing class using remove](#removing-class-using-remove)
- [Adding Text to HTML element](#adding-text-to-html-element)
- [Adding Text content using textContent](#adding-text-content-using-textcontent)
- [Adding Text Content using innHTML](#adding-text-content-using-innhtml)
- [Text Content](#text-content)
- [Inner HTML](#inner-html)
- [Adding style](#adding-style)
- [Adding Style Color](#adding-style-color)
- [Adding Style Background Color](#adding-style-background-color)
- [Adding Style Font Size](#adding-style-font-size)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
- [DOM: Mini project 1](#dom-mini-project-1)
- [Document Object Model (DOM) - Day 1](#document-object-model-dom---day-1)
- [Getting Element](#getting-element)
- [Getting elements by tag name](#getting-elements-by-tag-name)
- [Getting elements by class name](#getting-elements-by-class-name)
- [Getting an element by id](#getting-an-element-by-id)
- [Getting elements by using querySelector methods](#getting-elements-by-using-queryselector-methods)
- [Adding attribute](#adding-attribute)
- [Adding attribute using setAttribute](#adding-attribute-using-setattribute)
- [Adding attribute without setAttribute](#adding-attribute-without-setattribute)
- [Adding class using classList](#adding-class-using-classlist)
- [Removing class using remove](#removing-class-using-remove)
- [Adding Text to HTML element](#adding-text-to-html-element)
- [Adding Text content using textContent](#adding-text-content-using-textcontent)
- [Adding Text Content using innerHTML](#adding-text-content-using-innerhtml)
- [Text Content](#text-content)
- [Inner HTML](#inner-html)
- [Adding style](#adding-style)
- [Adding Style Color](#adding-style-color)
- [Adding Style Background Color](#adding-style-background-color)
- [Adding Style Font Size](#adding-style-font-size)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
- [DOM: Mini project 1](#dom-mini-project-1)
# Day 21
@ -57,7 +57,7 @@ We can access already created element or elements using JavaScript. To access or
```html
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>Document Object Model</title>
</head>
@ -74,7 +74,7 @@ We can access already created element or elements using JavaScript. To access or
#### 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
// syntax
@ -84,7 +84,7 @@ document.getElementsByTagName('tagname')
```js
const allTitles = document.getElementsByTagName('h1')
console.log(allTitles) //HTMCollections
console.log(allTitles) //HTMLCollections
console.log(allTitles.length) // 4
for (let i = 0; i < allTitles.length; i++) {
@ -104,7 +104,7 @@ document.getElementsByClassName('classname')
```js
const allTitles = document.getElementsByClassName('title')
console.log(allTitles) //HTMCollections
console.log(allTitles) //HTMLCollections
console.log(allTitles.length) // 4
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.
```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('.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.
@ -158,7 +158,7 @@ An attribute is added in the opening tag of HTML which gives additional informat
```js
const titles = document.querySelectorAll('h1')
titles[3].class = 'title'
titles[3].className = 'title'
titles[3].id = 'fourth-title'
```
@ -234,7 +234,7 @@ It value we assign is going to be a string of HTML elements.
```html
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>JavaScript for Everyone:DOM</title>
</head>
@ -264,7 +264,7 @@ The innerHTML property can allow us also to remove all the children of a parent
```html
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>JavaScript for Everyone:DOM</title>
</head>
@ -378,7 +378,7 @@ As you have notice, the properties of css when we use it in JavaScript is going
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>JavaScript for Everyone:DOM</title>
</head>

@ -1,25 +1,25 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:21 Day </title>
<title>30DaysOfJavaScript:21 Day </title>
</head>
<body>
<div class="wrapper">
<h1>Asabeneh Yetayeh challenges in 2020</h1>
<h2>30DaysOfJavaScript Challenge</h2>
<ul>
<li>30DaysOfPython Challenge Done</li>
<li>30DaysOfJavaScript Challenge Ongoing</li>
<li>30DaysOfReact Challenge Coming</li>
<li>30DaysOfFullStack Challenge Coming</li>
<li>30DaysOfDataAnalysis Challenge Coming</li>
<li>30DaysOfReactNative Challenge Coming</li>
<li>30DaysOfMachineLearning Challenge Coming</li>
</ul>
</div>
<script src="./scripts/main.js"></script>
<div class="wrapper">
<h1>Asabeneh Yetayeh challenges in 2020</h1>
<h2>30DaysOfJavaScript Challenge</h2>
<ul>
<li>30DaysOfPython Challenge Done</li>
<li>30DaysOfJavaScript Challenge Ongoing</li>
<li>30DaysOfReact Challenge Coming</li>
<li>30DaysOfFullStack Challenge Coming</li>
<li>30DaysOfDataAnalysis Challenge Coming</li>
<li>30DaysOfReactNative Challenge Coming</li>
<li>30DaysOfMachineLearning Challenge Coming</li>
</ul>
</div>
<script src="./scripts/main.js"></script>
</body>

@ -1,21 +1,21 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:22 Day: Number Generator </title>
<title>30DaysOfJavaScript:22 Day: Number Generator </title>
</head>
<body>
<h1>Number Generator</h1>
<h2>30DaysOfJavaScript:DOM Day 2</h2>
<h3>Author: Asabeneh Yetayeh</h3>
<div class="wrapper">
<h1>Number Generator</h1>
<h2>30DaysOfJavaScript:DOM Day 2</h2>
<h3>Author: Asabeneh Yetayeh</h3>
<div class="wrapper">
</div>
</div>
<script src="./scripts/main.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -1,28 +1,28 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:22 Day: World Countries List</title>
<title>30DaysOfJavaScript:22 Day: World Countries List</title>
</head>
<body>
<header>
<h2>World Countries List</h2>
<header>
<h2>World Countries List</h2>
<h4 id="total-countries"></h4>
<h3>30DaysOfJavaScript:DOM-Day-2</h3>
<h3>Author: Asabeneh Yetayeh</h3>
<h4 id="total-countries"></h4>
<h3>30DaysOfJavaScript:DOM-Day-2</h3>
<h3>Author: Asabeneh Yetayeh</h3>
</header>
</header>
<div class="countries-container">
<div class="countries-wrapper">
<div class="countries-container">
<div class="countries-wrapper">
</div>
</div>
</div>
</div>
<script src="./data/countries.js"></script>
<script src="./js/script.js"></script>
<script src="./data/countries.js"></script>
<script src="./js/script.js"></script>
</body>

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:22 Day: Challenge Info</title>
<title>30DaysOfJavaScript:22 Day: Challenge Info</title>
</head>
<body>
<div class="wrapper">
</div>
<div class="wrapper">
</div>
<script src="./data/challenges_info.js"></script>
<script src="./js/script.js"></script>
<script src="./data/challenges_info.js"></script>
<script src="./js/script.js"></script>
</body>

@ -19,18 +19,18 @@
![Thirty Days Of JavaScript](../images/banners/day_1_23.png)
- [Day 22](#day-22)
- [DOM(Document Object Model)-Day 3](#domdocument-object-model-day-3)
- [Event Listeners](#event-listeners)
- [Click](#click)
- [Double Click](#double-click)
- [Mouse enter](#mouse-enter)
- [Getting value from an input element](#getting-value-from-an-input-element)
- [input value](#input-value)
- [input event and change](#input-event-and-change)
- [blur event](#blur-event)
- [keypress, keydow and keyup](#keypress-keydow-and-keyup)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
- [DOM(Document Object Model)-Day 3](#domdocument-object-model-day-3)
- [Event Listeners](#event-listeners)
- [Click](#click)
- [Double Click](#double-click)
- [Mouse enter](#mouse-enter)
- [Getting value from an input element](#getting-value-from-an-input-element)
- [input value](#input-value)
- [input event and change](#input-event-and-change)
- [blur event](#blur-event)
- [keypress, keydow and keyup](#keypress-keydow-and-keyup)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
# Day 22
@ -174,7 +174,7 @@ By now you are familiar with addEventListen method and how to attach event liste
List of events:
- 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
- mouseleave - when the mouse pointer leave the element
- mousemove - when the mouse pointer move on the element

@ -1,21 +1,21 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:23 Day: Number Generator </title>
<title>30DaysOfJavaScript:23 Day: Number Generator </title>
</head>
<body>
<h1>Number Generator</h1>
<h2>30DaysOfJavaScript:DOM Day 2</h2>
<h3>Author: Asabeneh Yetayeh</h3>
<div class="wrapper">
<h1>Number Generator</h1>
<h2>30DaysOfJavaScript:DOM Day 2</h2>
<h3>Author: Asabeneh Yetayeh</h3>
<div class="wrapper">
</div>
</div>
<script src="./scripts/main.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -1,14 +1,14 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:23 Day: Keyboard Key </title>
<title>30DaysOfJavaScript:23 Day: Keyboard Key </title>
</head>
<body>
<script src="./scripts/main.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -1,39 +1,39 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>Solar System: Document Object Model:30 Days Of JavaScript</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500,600,700&display=swap" rel="stylesheet">
<title>Solar System: Document Object Model:30 Days Of JavaScript</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,500,600,700&display=swap" rel="stylesheet">
</head>
<body>
<header>
<h1>Calculate a weight of an object on a planet</h1>
<header>
<h1>Calculate a weight of an object on a planet</h1>
<input type="text" id="mass" placeholder="Mass in Kilogram" />
<select>
<option value='none'>--select planet-- </option>
</select>
<button>Calculate weight</button>
<input type="text" id="mass" placeholder="Mass in Kilogram" />
<select>
<option value='none'>--select planet-- </option>
</select>
<button>Calculate weight</button>
</header>
<main>
<div class="flex-container">
<div class="flex-item image">
<img src='./images/earth.png' class="planet-image" />
</div>
<div class="flex-item description"></div>
</header>
<main>
<div class="flex-container">
<div class="flex-item image">
<img src='./images/earth.png' class="planet-image" />
</div>
<div class="flex-item description"></div>
</div>
</div>
</main>
</main>
<script src="./scripts/main.js"></script>
<script src="./scripts/main.js"></script>
</body>
</html>

@ -2,36 +2,36 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>World Countries Data</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" />
<link rel="stylesheet" href="./css/style.css" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>World Countries Data</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" />
<link rel="stylesheet" href="./css/style.css" />
</head>
<body>
<header id="countries">
<h2>World Countries Data</h2>
<p class="subtitle"></p>
<p class="feedback"></p>
</header>
<main>
<header id="countries">
<h2>World Countries Data</h2>
<p class="subtitle"></p>
<p class="feedback"></p>
</header>
<main>
<div class="wrapper">
<div class="graph-buttons">
<button class="population">Population</button>
<button class="languages">Languages</button>
</div>
<h4 class="graph-title"></h4>
<div class="graphs">
<div class="graph-wrapper" id="stat"></div>
</div>
</div>
</main>
<div class="wrapper">
<div class="graph-buttons">
<button class="population">Population</button>
<button class="languages">Languages</button>
</div>
<h4 class="graph-title"></h4>
<div class="graphs">
<div class="graph-wrapper" id="stat"></div>
</div>
</div>
</main>
<script src="./data/countries_data.js"></script>
<script src="./js/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./js/main.js"></script>
</body>

@ -1,5 +1,5 @@
<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/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
@ -14,13 +14,13 @@
</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)
- [Day 25](#day-25)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
# Day 25

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:11 Day </title>
<title>30DaysOfJavaScript:11 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<script src="./data/countries.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:11 Day </title>
<title>30DaysOfJavaScript:11 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:11 Day </title>
<title>30DaysOfJavaScript:11 Day </title>
</head>
<body>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<h1>30DaysOfJavaScript:11 Day</h1>
<h2>Destructuring and Spread</h2>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -14,15 +14,15 @@
</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)
- [Day 29](#day-29)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
# Day 29
@ -41,4 +41,4 @@
🎉 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)

@ -2,24 +2,24 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link
href="https://fonts.googleapis.com/css?family=Aldrich|Lato:300,400,700|Montserrat:300,400,500|Nunito:300,400,600|Oswald|Raleway+Dots|Raleway:300,400|Roboto:300,400,500&display=swap"
rel="stylesheet">
<script src="https://kit.fontawesome.com/ce3e7ed90f.js" crossorigin="anonymous"></script>
<title>30Days Of JavaScript: 29 Project 1</title>
<link
href="https://fonts.googleapis.com/css?family=Aldrich|Lato:300,400,700|Montserrat:300,400,500|Nunito:300,400,600|Oswald|Raleway+Dots|Raleway:300,400|Roboto:300,400,500&display=swap"
rel="stylesheet">
<script src="https://kit.fontawesome.com/ce3e7ed90f.js" crossorigin="anonymous"></script>
<title>30Days Of JavaScript: 29 Project 1</title>
</head>
<body>
<div>
<div>
</div>
</div>
<script src="./scripts/main.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -1,16 +1,16 @@
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript: Day 29 - Project 2 </title>
<title>30DaysOfJavaScript: Day 29 - Project 2 </title>
</head>
<body>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
<script src="./data/countries_data.js"></script>
<script src="./scripts/main.js"></script>
</body>

@ -17,7 +17,7 @@
<div>
<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>
@ -26,10 +26,11 @@
![Thirty Days Of JavaScript](../images/banners/day_1_30.png)
- [Day 30](#day-30)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
- [Exercises](#exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
- [Testimony](#testimony)
# Day 30
@ -39,7 +40,7 @@
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.
@ -55,6 +56,7 @@
🌕 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)

@ -0,0 +1 @@
console.log('Salam, dünya!')

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title>30 Günlük JavaScript dərsləri</title>
</head>
<body>
<h1>30 Günlük JavaScript:01 Gün</h1>
<h2>Giriş</h2>
<button onclick="alert('30 Günlük JavaScript dərslərinə xoş gəlmişsiniz');">Kliklə</button>
<script src="helloworld.js"></script>
<script src="introduction.js"></script>
<script src="variables.js"></script>
<script src="main.js"></script>
</body>
</html>

@ -0,0 +1 @@
console.log('30 Günlük JS dərsləri')

@ -0,0 +1,4 @@
// bir faylda müəyyən olunmuş dəyişənlər digərindən əlçatandır
console.log(firstName, lastName, country, city, age, isMarried)
console.log(gravity, boilingPoint, PI) // 9.81, 100, 3.14
console.log(name, job, live)

@ -0,0 +1,20 @@
// Müxtəlif verilənlər tipindən istifadə edərək dəyişənlərin yaradılmasə
let firstName = 'Asabeneh' // ad
let lastName = 'Yetayeh' // soyad
let country = 'Finland' // ölkə
let city = 'Helsinki' // paytaxt
let age = 100 // yaş
let isMarried = true
// ədəd tipli dəyişənlərin sabit açar sözü ilə yaradılması
const gravity = 9.81 // Fizikada istifadə olunan qravitasiya sabiti
const boilingPoint = 100 // Normal atmosfer təzyiqində suyun qaynama tempraturu
const PI = 3.14 // Geometrik sabit
// Yalnız bir açar sözü istifadə etməklə müxtəlif dəyişənlər vergüllə ayrılmış şəkildə yaradıla bilər
let name = 'Asabeneh', //ad
job = 'teacher', // vəzifə
live = 'Finland' // ölkə

@ -0,0 +1,662 @@
# 30 Günlük JavaScript dərsləri
| # Gün | Mövzular |
| ----- | :-------------------------------------------------------------------------------------------------------------------------------------------------: |
| 01 | [Giriş](./readMe.md) |
| 02 | [Data Types](./02_Day_Data_types/02_day_data_types.md) |
| 03 | [Booleans, Operators, Date](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) |
| 04 | [Conditionals](./04_Day_Conditionals/04_day_conditionals.md) |
| 05 | [Arrays](./05_Day_Arrays/05_day_arrays.md) |
| 06 | [Loops](./06_Day_Loops/06_day_loops.md) |
| 07 | [Functions](./07_Day_Functions/07_day_functions.md) |
| 08 | [Objects](./08_Day_Objects/08_day_objects.md) |
| 09 | [Higher Order Functions](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) |
| 10 | [Sets and Maps](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) |
| 11 | [Destructuring and Spreading](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) |
| 12 | [Regular Expressions](./12_Day_Regular_expressions/12_day_regular_expressions.md) |
| 13 | [Console Object Methods](./13_Day_Console_object_methods/13_day_console_object_methods.md) |
| 14 | [Error Handling](./14_Day_Error_handling/14_day_error_handling.md) |
| 15 | [Classes](./15_Day_Classes/15_day_classes.md) |
| 16 | [JSON](./16_Day_JSON/16_day_json.md) |
| 17 | [Web Storages](./17_Day_Web_storages/17_day_web_storages.md) |
| 18 | [Promises](./18_Day_Promises/18_day_promises.md) |
| 19 | [Closure](./19_Day_Closures/19_day_closures.md) |
| 20 | [Writing Clean Code](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) |
| 21 | [DOM](./21_Day_DOM/21_day_dom.md) |
| 22 | [Manipulating DOM Object](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) |
| 23 | [Event Listeners](./23_Day_Event_listeners/23_day_event_listeners.md) |
| 24 | [Mini Project: Solar System](./24_Day_Project_solar_system/24_day_project_solar_system.md) |
| 25 | [Mini Project: World Countries Data Visulalization 1](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) |
| 26 | [Mini Project: World Countries Data Visulalization 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) |
| 27 | [Mini Project: Portfolio](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) |
| 28 | [Mini Project: Leaderboard](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) |
| 29 | [Mini Project:Animating characters](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) |
| 30 | [Final Projects](./30_Day_Mini_project_final/30_day_mini_project_final.md) |
🧡🧡🧡 Xoş kodlamalar 🧡🧡🧡
<div>
<small><strong>Müəllifi</strong> dəstəkləməklə daha çox təhsil materialı yaratmasına kömək ola bilərsiniz</small> <br />
<a href = "https://www.paypal.me/asabeneh"><img src='../images/paypal_lg.png' alt='Paypal Logo' style="width:10%"/></a>
</div>
<div align="center">
<h1> 30 Günlük JavaScript: Giriş</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Yanvar, 2020</small>
</sub>
<div>
🇬🇧 [English](./readMe.md)
🇪🇸 [Spanish](./Spanish/readme.md)
🇷🇺 [Russian](./RU/README.md)
Az [Azerbaijan](./Azerbaijani/readMe.md)
</div>
</div>
</div>
[Gün 2 >>](./02_Day_Data_types/02_day_data_types.md)
![30 Günlük JavaScript dərsləri](../images/day_1_1.png)
- [30 Günlük JavaScript dərsləri](#30-days-of-javascript)
- [📔 Gün 1](#-day-1)
- [Giriş](#introduction)
- [İlkin tələblər](#requirements)
- [Hazırlıq](#setup)
- [Node.js yüklə](#install-nodejs)
- [Brauzer](#browser)
- [Google Chrome yüklənməsi](#installing-google-chrome)
- [Google Chrome brauzer konsolu açmaq](#opening-google-chrome-console)
- [Brauzer konsolunda kod yazılması](#writing-code-on-browser-console)
- [Console.log](#consolelog)
- [Console.log - birneçə arqument ilə](#consolelog-with-multiple-arguments)
- [Şərhlər](#comments)
- [Sintaksis](#syntax)
- [Riyazi əməliyyatlar](#arithmetics)
- [Kod editoru](#code-editor)
- [Visual Studio Code'un yüklənməsi](#installing-visual-studio-code)
- [Visual Studio Code istifadəsi](#how-to-use-visual-studio-code)
- [Veb səhifəyə JavaScript əlavə edilməsi](#adding-javascript-to-a-web-page)
- [Sətirdaxili (inline) skript](#inline-script)
- [Daxili (internal) skript](#internal-script)
- [Xarici skript](#external-script)
- [Birneçə xarici skript](#multiple-external-scripts)
- [Verilənlərin tiplərinə giriş](#introduction-to-data-types)
- [Ədəd tipləri](#numbers)
- [Sətir tipləri](#strings)
- [Məntiqi tiplər](#booleans)
- [Undefined](#undefined)
- [Null](#null)
- [Verilənlərin tiplərinin yoxlanılması](#checking-data-types)
- [Şərhlər (daha artıq)](#comments-again)
- [Dəyişənlər](#variables)
- [💻 Gün 1: Tapşırıqlar](#-day-1-exercises)
# 📔 Gün 1
## Giriş
30 günlük JavaScript proqramlaşdırma müsabiqəsində iştirak etmək qərarına gəldiyiniz üçün sizi **təbrik edirik**. Bu çağırışda siz JavaScript proqramçısı olmaq üçün lazım olan hər şeyi və ümumiyyətlə, proqramlaşdırmanın bütün konsepsiyasını öyrənəcəksiniz. Müsabiqənin sonunda siz 30DaysOfJavaScript proqramlaşdırma testini tamamlama sertifikatı alacaqsınız. Yardıma ehtiyacınız olarsa və ya başqalarına kömək etmək istəyirsinizsə, rəsmi [telegram qrupuna](https://t.me/ThirtyDaysOfJavaScript) qoşula bilərsiniz
**30GünlükJavaScript** çağırışı həm yeni başlayanlar, həm də təcrübəli JavaScript proqramçıları üçün bələdçidir. JavaScript-ə xoş gəlmisiniz. JavaScript internetin dilidir. Mən JavaScript istifadə etməkdən və öyrətməkdən həzz alıram və ümid edirəm ki, siz də bunu edəcəksiniz.
Bu addım-addım JavaScript dərslərində siz bəşəriyyət tarixində ən populyar proqramlaşdırma dili olan JavaScript-i öyrənəcəksiniz.JavaScript **_veb-saytlara interaktivlik əlavə etmək, mobil proqramlar, masaüstü proqramlar, oyunlar hazırlamaq_** üçün istifadə olunur və bu gün JavaScript hətta **_maşın öyrənməsi_****_AI (süni intellekt)_** üçün istifadə edilə bilər.
**_JavaScript (JS)_** son illərdə populyarlığı artıb və son altı ildir ki, ardıcıl olaraq ən məhşur və ən çox istifadə olunan proqramlaşdırma dilidir
Mənbə: Github.
## Tələblər
İlkin olaraq heç bir proqramlaşdırma biliyi tələb olunmur. Yalnız ehtiyacınız var:
1. Motivasiya
2. Kompüter
3. Internet
4. Brauzer
5. Kod yazmaq üçün editor
## Hazırlıq
İnanıram ki, sizdə proqramçı olmaq üçün kompüter, internet, motivasiya və güclü istək var. Bunlara sahibsinizsə, başlamaq üçün hər şeyiniz var.
### Node.js-in yüklənilməsi
İndi olmasa belə daha sonrakı addımlar üçün Node-a ehtiyaciniz var. Yükləmək üçün [buraya](https://nodejs.org/en/) istinad edin.
![Node Yüklənməsi](../images/download_node.png)
Yükləndikdən sonra quraşdırılma üçün
![Node quraşdırılması](../images/install_node.png)
Əməliyyat sistemi terminalımızı açaraq maşınımızda node quraşdırılıb-quraşdırılmadığını yoxlaya bilərik.
```sh
asabeneh $ node -v
v12.14.0
```
Bu dərsliyi hazırlayarkən mən Node versiyası 12.14.0-dan istifadə edirdim, lakin indi yükləmək üçün Node.js-in tövsiyə olunan versiyası v14.17.6-dır.
### Brauzer
Hazırda bir çox brauzer mövcud olsa da müəllif Google Chrome istifadəsini tövsiyə edir.
#### Google Chrome yükləmək
Google Chrome sizdə mövcud deyilsə bu [linkə](https://www.google.com/chrome/) istinad edin. Biz brauzer konsolunda kiçik JavaScript kodu yaza bilərik, lakin ciddi proqramların hazırlanması üçün brauzer konsolundan istifadə etmirik.
![Google Chrome](../images/google_chrome.png)
#### Google Chrome konsola giriş
Siz Google Chrome konsolunu brauzerin yuxarı sağ küncündə üç nöqtəyə klikləməklə, _Əlavə alətlər -> Tərtibatçı alətləri_ seçməklə və ya klaviatura qısa yolundan istifadə etməklə aça bilərsiniz. Mən qısayollardan istifadə etməyi üstün tuturam.
![Brauzerə giriş](../images/opening_developer_tool.png)
Klaviatura qısayolu ilə brauzer açmaq üçün
```sh
Mac
Command+Option+J
Windows/Linux:
Ctl+Shift+J
```
![Konsolu açmaq](../images/opening_chrome_console_shortcut.png)
Google Chrome konsolunu açdıqdan sonra işarələnmiş düymələri araşdırmağa çalışın. Biz vaxtımızın çox hissəsini Konsolda keçirəcəyik. Konsol JavaScript kodunuzun mövcud olduğu yerdir. Google Console V8 mühərriki JavaScript kodunuzu maşın koduna tərcümə edir.
Gəlin Google Chrome konsolunda JavaScript kodu yazaq:
![Konsolda kodun yazılması](../images/js_code_on_chrome_console.png)
#### Brauzer konsolunda kodun yazılması
Biz istənilən JavaScript kodunu Google konsolunda və ya istənilən brauzer konsolunda yaza bilərik. Bununla belə, bu problem üçün biz yalnız Google Chrome konsoluna diqqət yetiririk. Konsolu aşağıdakılardan istifadə edərək açın:
```sh
Mac
Command+Option+I
Windows:
Ctl+Shift+I
```
##### Console.log
İlk JavaScript kodumuzu yazmaq üçün biz daxili funksiyadan istifadə etdik **console.log()**. Biz arqumenti giriş məlumatları kimi ötürdük və funksiya çıxışı göstərir. Biz console.log() funksiyasında giriş məlumatı və ya arqument kimi "Salam, Dünya"nı ötürdük.
```js
console.log('Salam, Dünya!')
```
##### Console.log - birneçə arqument ilə
**console.log()** funksiyasi vergüllə ayrılmış istənilən sayda parametri qəbul edə bilər.
Sintaksis: **console.log(param1, param2, param3)**
![console log - birneçə arqument ilə](../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')
```
Yuxarıdakı kod parçasından göründüyü kimi, _console.log()_ çoxlu arqument qəbul edə bilər.
Təbrik edirik! Siz ilk JavaScript kodunuzu _console.log()_ istifadə edərək yazdınız.
##### Şərhlər
Kodumuza şərhlər əlavə edirik. Kodu daha oxunaqlı etmək və kodumuzda qeydlər daxil etmək üçün şərhlər çox vacibdir. JavaScript kodumuzun şərh hissəsini qeydə almır və maşın dilinə tərcümə etmir. JavaScript-də // ilə başlayan hər hansı mətn sətiri şərhdir və həmçinin buna /\* \*/ kimi əlavə edilən hər şey də şərhdir.
**Nümunə: Tək sətirli şərhlər**
// Bu bir şərhdir
// Bu da bir şərhdir
// Bu da həmçinin
**Nümunə: Çoxsətirli şərhlər**
/*
Çoxsətirli şərhlər
Çoxsətirli şərhlər bir neçə sətiri ehtiva edə bilir
JavaScript web-in dilidir
*/
##### Sintaksis
Proqramlaşdırma dilləri insan dillərinə bənzəyir. İngilis və ya bir çox başqa dil mənalı mesajı çatdırmaq üçün sözlər, ifadələr, cümlələr, mürəkkəb cümlələr və sair istifadə edir. Sintaksisin ingiliscə mənası _dildə yaxşı formalaşmış cümlələr yaratmaq üçün söz və ifadələrin düzülüşüdür_. Sintaksisin texniki tərifi kompüter dilində ifadələrin strukturudur. Proqramlaşdırma dillərində sintaksis var. JavaScript proqramlaşdırma dilidir və digər proqramlaşdırma dilləri kimi onun da öz sintaksisi var. JavaScript-in başa düşdüyü sintaksisi yazmasaq, o, müxtəlif növ xətaları bizə qaytaracaq. Müxtəlif növ JavaScript xətalarını daha sonra araşdıracağıq. Hələlik gəlin sintaksis səhvlərinə baxaq.
![Errorlar](../images/raising_syntax_error.png)
Mən qəsdən səhv etdim. Nəticədə, konsol sintaksis səhvlərini qaytarır. Əslində, sintaksis çox informativdir. Hansı növ səhvə yol verildiyini bildirir. Səhv rəyi təlimatını oxumaqla biz sintaksisi düzəldə və problemi həll edə bilərik. Proqramdakı xətaların müəyyən edilməsi və aradan qaldırılması prosesi "debugging" adlanır. Gəlin səhvləri düzəldək:
```js
console.log('Hello, World!')
console.log('Hello, World!')
```
İndiyə qədər biz _console.log()_ istifadə edərək mətnin necə göstərildiyini gördük. Əgər biz _console.log()_ istifadə edərək mətni və ya sətri çap ediriksə, mətn tək dırnaqlar, qoşa dırnaqlar və ya əks dırnaqlar (backtick) içərisində olmalıdır.
**Nümunə:**
```js
console.log('Hello, World!')
console.log("Hello, World!")
console.log(`Hello, World!`)
```
#### Riyazi əməliyyatlar
İndi gəlin ədəd tipli dəyişənlər üzərində Google Chrome konsolunda _console.log()_ istifadə edərək JavaScript kodlarının yazılmasına aid nümunələri məşq edək.
Mətnə əlavə olaraq JavaScript-dən istifadə edərək riyazi hesablamalar da edə bilərik. Aşağıdakı sadə hesablamaları aparaq.
Konsol **_console.log()_** funksiyası olmadan birbaşa arqumentlər qəbul edə bilər. Bununla belə, o, dərslikdə daha əvvəldə daxil edilmişdir, çünki bu nümunələrin əksəriyyəti funksiyadan istifadənin məcburi olduğu mətn redaktorunda baş verəcəkdir. Konsoldakı təlimatlarlı birbaşa nəzərdən keçirə bilərsiniz.
![Riyazi hesablamalar](../images/arithmetic.png)
```js
console.log(2 + 3) // Toplama
console.log(3 - 2) // Çıxma
console.log(2 * 3) // Vurma
console.log(3 / 2) // Bölmə
console.log(3 % 2) // Qalığın tapılması
console.log(3 ** 2) // Qüvvət üstü. Yəni, 3 ** 2 == 3 * 3
```
### Mətn redaktoru
Kodlarımızı brauzer konsoluna yaza bilərik, lakin bu, daha böyük layihələr üçün əlverişli deyil və ya bəzi hallarda mümkünsüzdür. Real iş mühitində proqramçılar kodlarını yazmaq üçün müxtəlif kod/mətn redaktorlarından istifadə edirlər. Bu 30 günlük JavaScript dərsliyində biz Visual Studio Code-dan istifadə edəcəyik.
#### Visual Studio Code-un yüklənməsi
Visual Studio Code çox məşhur açıq mənbəli mətn redaktorudur. [Visual Studio Code-u yükləmə](https://code.visualstudio.com/) tövsiyə edərdim, lakin başqa redaktorların tərəfdarısınızsa, əlinizdə olanları istifadə etməkdən çəkinməyin.
![Vscode](../images/vscode.png)
Yüklədikdən sonra mətn redaktoru artıq istifadəyə hazırdır.
#### Visual Studio Code-u necə istifadə etməli
Yüklənmə uğurla başa çatdıqdan sonra Visual Studio Code ikonuna 2 ardıcıl klik edərək onu başlada bilərsiniz
![Vscode istifadəçi interfeysi](../images/vscode_ui.png)
![Vscode-da proyekt əlavə etmək](../images/adding_project_to_vscode.png)
![Vscode-da mövcud proyekti açmaq](../images/opening_project_on_vscode.png)
![Skript faylı](../images/scripts_on_vscode.png)
![Live Server əlavəsinin yüklənilməsi](../images/vsc_live_server.png)
![Skriptin icrası](./images/running_script.png)
![Kodun icrası](../images/launched_on_new_tab.png)
## Veb səhifəyə JavaScript əlavə olunması
JavaScript kodu veb səhifəyə 3 üsulla əlavə edilə bilər:
- **_Sətirdaxili skript_**
- **_Daxili skript_**
- **_Xarici fayl ilə skript_**
- **_Birneçə xarici faylla skript_**
Aşağıdakı bölmələr veb səhifənizə JavaScript kodu əlavə etməyin müxtəlif yollarını göstərir.
### Sətirdaxili skript
İş masanızda və ya istənilən yerdə layihə qovluğu yaradın, onu 30DaysOfJS adlandırın və layihə qovluğunda **_index.html_** faylı yaradın. Sonra aşağıdakı kodu fayla əlavə edib onu brauzerdə açın, məsələn [Chrome](https://www.google.com/chrome/) ilə.
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript: Sətirdaxili skript</title>
</head>
<body>
<button onclick="alert('30DaysOfJavaScript dərsliyinə xoş gəlmişsiniz')">Kliklə</button>
</body>
</html>
```
İndi siz ilk daxili skriptinizi yazdınız. Biz _alert()_ daxili funksiyasından istifadə edərək pop-up xəbərdarlıq mesajı yarada bilərik.
### Daxili skript
Daxili skript _head_ və ya _body_ ilə yazıla bilər, lakin onu HTML sənədinin gövdəsinə yerləşdirməyə üstünlük verilir.
Əvvəlcə səhifənin baş hissəsinə yazaq.
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript: Daxili skript</title>
<script>
console.log('30DaysOfJavaScript-ə xoş gəlmişsiniz')
</script>
</head>
<body></body>
</html>
```
Çox vaxt daxili skripti belə yazırıq. JavaScript kodunun faylın gövdəsinə (body) bölməsinə yazılması ən çox üstünlük verilən seçimdir. console.log() saytından çıxışı görmək üçün brauzer konsolunu açın
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfScript: Daxili skript</title>
</head>
<body>
<button onclick="alert('30DaysOfJavaScript-ə xoş gəlmişsiniz');">Kliklə</button>
<script>
console.log('30DaysOfJavaScript-ə xoş gəlmişsiniz')
</script>
</body>
</html>
```
console.log() saytından çıxışı görmək üçün brauzer konsolunu açın
![JS kodu redaktorda](../images/js_code_vscode.png)
### Xarici kod skripti
Daxili skriptə bənzər şəkildə, xarici skript bağlantısı başlıqda (head) və ya gövdədə (body) ola bilər, lakin onun gövdəyə yerləşdirilməsinə üstünlük verilir.
Əvvəlcə .js uzantılı xarici JavaScript faylı yaratmalıyıq. .js uzantısı ilə bitən bütün fayllar JavaScript fayllarıdır. Layihə qovluğunda introduction.js adlı fayl yaradın və aşağıdakı kodu yazın və bu .js faylını gövdənin aşağı hissəsində əlaqələndirin.
```js
console.log('30 Günlük JS dərsləri')
```
_head_ hissəsində JavaScript faylına istinad:
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript: Xarici skript faylı</title>
<script src="introduction.js"></script>
</head>
<body></body>
</html>
```
_body_ hissəsində JavaScript faylına istinad:
```html
<!DOCTYPE html>
<html>
<head>
<title>30DaysOfJavaScript: Xarici skript faylı</title>
</head>
<body>
<!-- Əvvəldə vurğuladığımız kimi həm head həm body hissəsində ola bilər -->
<!-- Lakin aşağıda göstərilən kimi (body hissəsində) olması arzuolunandır -->
<script src="introduction.js"></script>
</body>
</html>
```
console.log() nəticəsini görmək üçün brauzer konsolunu açın.
### Birneçə xarici skript faylına istinad
Biz həmçinin bir neçə xarici JavaScript faylına veb səhifədə istinad edə bilərik.
30DaysOfJS qovluğunda helloworld.js faylı yaradın və aşağıdakı kodu yazın.
```js
console.log('Salam, dünya!')
```
```html
<!DOCTYPE html>
<html>
<head>
<title>Birneçə xarici skript faylına istinad</title>
</head>
<body>
<script src="helloworld.js"></script>
<script src="introduction.js"></script>
</body>
</html>
```
_Main.js_ faylınız bütün digər skriptlərdən sonra daxil edilməlidir. Bunu xatırlamaq çox vacibdir.
![Birneçə fayl](../images/multiple_script.png)
## Verilənlər tiplərinə giriş
JavaScript-də və digər proqramlaşdırma dillərində müxtəlif növ məlumat növləri mövcuddur. Aşağıdakılar JavaScript primitiv verilən tipləridir:_String, Number, Boolean, undefined, Null_ və _Symbol_.
### Ədədlər (Numbers)
- İnteger: Integer (mənfi, sıfır və müsbət) ədədlər
Nümunə:
... -3, -2, -1, 0, 1, 2, 3 ...
- Tam hissəli ədədlər: Onluq (Decimal) ədədlər
Nümunə:
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
### Sətir (String) tipli verilənlər
İki tək dırnaq, qoşa dırnaq və ya əks istiqamətli dırnaqlar arasında bir və ya daha çox simvol çoxluğudur.
**Nümunə:**
```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'
```
### Məntiqi ifadələr
Məntiqi tiplər yalnız iki mümkün qiymətdən birini ala bilən ifadələrdir. İstənilən müqayisə əməliyyatı _true_ və ya _false_ qiymətlərinin birindən ibarət nəticə qaytarır.
**Nümunə:**
```js
true
false
```
### Undefined
JavaScript-də dəyişənə ilkin qiymət təyin etməsək, _undefined_ tipi verilir. Bundan əlavə, funksiya heç nə qaytarmırsa, susmaya görə _undefined_ qaytarır.
```js
let firstName
console.log(firstName) // undefined, çünki dəyişənə ilkin qiymət təyin edilməyib
```
### Null
JavaScript-də null boş dəyər deməkdir.
```js
let emptyValue = null
```
## Verilənlər tiplərinin yoxlanılması
Hər hansi müəyyən olunmuş dəyişənin tipini tapmaq üçün **typeof** operatoru istifadə oluna bilər. Nümunəyə nəzər yetirin.
```js
console.log(typeof 'Asabeneh') // string
console.log(typeof 5) // number
console.log(typeof true) // boolean
console.log(typeof null) // object type
console.log(typeof undefined) // undefined
```
## Şərhlər (daha artıq)
Bildiyimiz kimi JavaScript-də şərh yazmaq digər proqramlaşdırma dillərinə olduğu kimidir. Kodunuzu daha oxunaqlı etmək üçün şərhlər vacibdir.
Şərh əlavə etməyin iki yolu var:
- _Təksətirli şərhlər_
- _Çoxsətirli şərhlər_
```js
// let firstName = 'Asabeneh'; tək sətirli şərh
// let lastName = 'Yetayeh'; tək sətirli şərh
```
Çoxsətirli şərhlər:
```js
/*
let location = 'Helsinki';
let age = 100;
let isMarried = true;
This is a Multiple line comment
*/
```
## Dəyişıənlər
Dəyişənlər məlumatların yaddaşda saxlanması üçün istifadə olunur. Dəyişən elan edildikdə, yaddaş yeri rezerv olunur. Dəyişən təyin edildikdə, yaddaş sahəsində həmin verilənlər saxlanılır. Dəyişən elan etmək üçün biz _var_, _let_ və ya _const_ açar sözlərindən istifadə edirik.
Qİyməti proqram daxilində dəyişən dəyişənlər üçün biz _let_ istifadə edirik. Məlumatlar ümumiyyətlə dəyişməzsə, yəni sabitlər üçün biz _const_ istifadə edirik. Məsələn, PI sabiti üçün biz _const_ istifadə edə bilərik. Bu dərslikdə _var_ istifadə etməyəcəyik və mən sizə ondan istifadə etməyi tövsiyə etmirəm. Bu, tövsiyə edilən yol deyil və təhlükəli məqamlara yol aça bilər. Var, let və const haqqında digər bölmələrdə ətraflı danışacağıq. Hələlik yuxarıdakı izahat kifayətdir.
Düzgün JavaScript dəyişən adı aşağıdakı qaydalara əməl etməlidir:
- Rəqəmlə başlaya bilməz.
- $ və _ istisna olmaqla xüsusi simvolların istifadəsinə icazə verilmir.
- Adətən camelCase konvensiyasına əsaslanaraq adlandırılır.
- Sözlər və ya dəyişən adının hissələri arasında boşluq olmaz.
Düzgün dəyişən adları nümunələri:
```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
```
Siyahıdakı birinci və ikinci dəyişənlər JavaScript-də elan etmək üçün camelCase konvensiyasına uyğundur. Bu dərslikdə biz camelCase dəyişənlərindən istifadə edəcəyik.
Yalnış elan olunmuş dəyişənlər:
```sh
first-name
1_num
num_#_1
```
Müxtəlif verilən tipləri ilə dəyişənləri elan edək. Dəyişən elan etmək üçün dəyişən adından əvvəl _let_ və ya _const_ açar sözündən istifadə etməliyik. Dəyişən adından sonra bərabər işarəsi (təyinat operatoru) və dəyəri (təyin edilmiş verilənlər) yazırıq.
```js
// Sintaksis
let nameOfVariable = value
```
**Nümunələr**
```js
// Müxtəlif verilənlər tipindən istifadə edərək dəyişənlərin yaradılmasə
let firstName = 'Asabeneh' // ad
let lastName = 'Yetayeh' // soyad
let country = 'Finland' // ölkə
let city = 'Helsinki' // paytaxt
let age = 100 // yaş
let isMarried = true
console.log(firstName, lastName, country, city, age, isMarried)
```
```sh
Asabeneh Yetayeh Finland Helsinki 100 true
```
```js
// ədəd tipli dəyişənlərin sabit açar sözü ilə yaradılması
let age = 100 // yaş
const gravity = 9.81 // Fizikada istifadə olunan qravitasiya sabiti
const boilingPoint = 100 // Normal atmosfer təzyiqində suyun qaynama tempraturu
const PI = 3.14 // Geometrik sabit
console.log(gravity, boilingPoint, PI)
```
```sh
9.81 100 3.14
```
```js
// Yalnız bir açar sözü istifadə etməklə müxtəlif dəyişənlər vergüllə ayrılmış şəkildə yaradıla bilər
let name = 'Asabeneh', //ad
job = 'teacher', // vəzifə
live = 'Finland' // ölkə
console.log(name, job, live)
```
```sh
Asabeneh teacher Finland
```
01_Giriş qovluqda _index.html_ faylını işə saldığınız zaman bunu əldə etməlisiniz:
![Gün 1](../images/day_1.png)
🌕 Təbrik edirik! Siz 1-ci günü yenicə tamamladınız. İndi beyniniz və əzələniz üçün bəzi fiziki hərəkətlər edin.
# 💻 Gün 1: Tapşırıqlar
1. _şərhlər kodu oxunaqlı edə bilər_ mətnini özündə ehtiva edən tək sətirli şərh yazın.
2. _30DaysOfJavaScript-ə xoş gəlmisiniz_ deyən başqa bir şərh yazın.
3. Şərhlərin kodu oxunaqlı, təkrar istifadəsi asan və məlumatlandırıcı edə biləcəyini deyən çoxsətirli şərh yazın
4. Variables.js faylı yaradın və dəyişənləri elan edin və sətir, boolean, undefined və null dəyişən tiplərini təyin edin
5. datatypes.js faylı yaradın və müxtəlif dəyişən tiplərini yoxlamaq üçün JavaScript **_typeof_** operatorundan istifadə edin.
6. İlkin qiymət təyin etmədən dörd dəyişəni elan edin
7. Təyin edilmiş ilkin qiymət olan dörd dəyişəni elan edin
8. Adınızı, soyadınızı, ailə vəziyyətinizi, ölkənizi və yaşınızı bir neçə sətirdə saxlamaq üçün dəyişənləri elan edin
9. Adınızı, soyadınızı, ailə vəziyyətinizi, ölkənizi və yaşınızı bir sətirdə saxlamaq üçün dəyişənləri elan edin
10. İki _myAge__yourAge_ dəyişənini elan edin və onlara ilkin qiymətlər təyin edin və brauzer konsoluna daxil olun.
```sh
I am 25 years old.
You are 30 years old.
```
🎉 TƏBRİK EDİRİK ! 🎉
[Gün 2 >>](./02_Day_Data_types/02_day_data_types.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, является комментарием или что-то в этом роде `/* */` является комментарием.
**Пример: Однострочный комментарийt**
**Пример: Однострочный комментарий**
```js
// Это первый комментарий

@ -0,0 +1,979 @@
<div align="center">
<h1> 30 Días de JavaScript: Tipos de Datos</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
</div>
</div>
[<< Día 1](../readMe.md)
![Thirty Days Of JavaScript](../images/banners/day_1_2.png)
- [📔 Día 2](#-Día-2)
- [Tipos de Datos](#tipos-de-datos)
- [Tipos de datos primitivos](#tipos-de-datos-primitivos)
- [Tipos de datos no primitivos](#tipos-de-datos-no-primitivos)
- [Números](#números)
- [Declaración de tipos de datos numéricos](#declaración-de-tipos-de-datos-numéricos)
- [Objeto matemático](#objeto-matemático)
- [Generador de números aleatorios](#generador-de-números-aleatorios)
- [Cadenas](#cadenas)
- [Concatenación de cadenas](#concatenación-de-cadenas)
- [Concatenar usando el operador de suma](#concatenar-usando-el-operador-de-suma)
- [Cadenas literales largas](#cadenas-literales-largas)
- [Secuencias de escape en cadenas](#secuencias-de-escape-en-cadenas)
- [Literales de plantilla](#literales-de-plantilla)
- [Métodos de cadena](#métodos-de-cadena)
- [Comprobación de tipos de datos y conversión](#comprobación-de-tipos-de-datos-y-conversión)
- [Comprobación de tipos de datos](#comprobación-de-tipos-de-datos)
- [Cambio del tipo de datos](#cambio-del-tipo-de-datos)
- [Cadena a Int](#cadena-a-int)
- [Cadena a Floatante](#cadena-a-floatante)
- [Flotante a Int](#flotante-a-int)
- [💻 Día 2: Ejercicios](#-día-2-ejercicios)
- [Ejercicio: Nivel 1](#ejercicio-nivel-1)
- [Ejercicio: Nivel 2](#ejercicio-nivel-2)
- [Ejercicios: Nivel 3](#ejercicios-nivel-3)
# 📔 Día 2
## Tipos de Datos
En la sección anterior, mencionamos un poco sobre los tipos de datos. Los datos o valores tienen tipos de datos. Los tipos de datos describen las características de los datos. Los tipos de datos se pueden dividir en dos:
1. Tipos de datos primitivos
2. Tipos de datos que no son primitivos (referencias de objetos)
### Tipos de datos primitivos
Los tipos de datos primitivos en JavaScript incluyen:
1. Números: enteros, flotantes
2. Cadenas: cualquier dato entre comillas simples, comillas dobles o comillas invertidas
3. Booleanos: valor verdadero o falso
4. Nulo - valor vacío o sin valor
5. Indefinido - una variable declarada sin un valor
Los tipos de datos que no son primitivos en JavaScript incluyen:
1. Objetos
2. Funciones
3. Matrices
Ahora, veamos qué significan exactamente los tipos de datos primitivos y no primitivos.
Los tipos de datos *primitivos* son tipos de datos inmutables (no modificables). Una vez que se crea un tipo de datos primitivo, no podemos modificarlo.
**Ejemplo:**
```js
let word = 'JavaScript'
```
Si intentamos modificar la cadena almacenada en la variable *word*, JavaScript debería generar un error. Cualquier tipo de datos bajo comillas simples, comillas dobles o comillas invertidas son un tipo de datos de cadena.
```js
word[0] = 'Y'
```
Esta expresión no cambia la cadena almacenada en la variable *word*. Entonces, podemos decir que las cadenas no son modificables o, en otras palabras, inmutables. Los tipos de datos primitivos se comparan por sus valores. Comparemos diferentes valores de datos. Vea el ejemplo a continuación:
```js
let numOne = 3
let numTwo = 3
console.log(numOne == numTwo) // Verdadero
let js = 'JavaScript'
let py = 'Python'
console.log(js == py) // Falso
let lightOn = true
let lightOff = false
console.log(lightOn == lightOff) // Falso
```
### Tipos de datos no primitivos
Los tipos de datos *no primitivos* son modificables o mutables. Podemos modificar el valor de los tipos de datos no primitivos después de su creación.
Veamos creando una matriz. Una matriz es una lista de valores de datos entre corchetes. Las matrices pueden contener tipos de datos iguales o diferentes. Los valores de matriz están referenciados por su índice. En el índice de matriz de JavaScript comienza en cero. Es decir, el primer elemento de una matriz se encuentra en el índice cero, el segundo elemento en el índice uno y el tercer elemento en el índice dos, etc.
```js
let nums = [1, 2, 3]
nums[0] = 10
console.log(nums) // [10, 2, 3]
```
Como puede ver, una matriz, que es un tipo de datos no primitivo, es mutable. Los tipos de datos no primitivos no se pueden comparar por valor. Incluso si dos tipos de datos no primitivos tienen las mismas propiedades y valores, no son estrictamente iguales.
```js
let nums = [1, 2, 3]
let numberos = [1, 2, 3]
console.log(nums == numbers) // Falso
let usuarioUno = {
nombre:'Asabeneh',
papel:'teaching',
pais:'Finland'
}
let usuarioDos = {
nombre:'Asabeneh',
papel:'teaching',
pais:'Finland'
}
console.log(usuarioUno == usuarioDos) // Falso
```
Como regla general, no comparamos tipos de datos no primitivos. No compare matrices, funciones u objetos.
Los valores no primitivos se conocen como tipos de referencia, porque se comparan por referencia en lugar de por valor. Dos objetos solo son estrictamente iguales si se refieren al mismo objeto subyacente.
```js
let nums = [1, 2, 3]
let numberos = nums
console.log(nums == numbers) // Verdadero
let usuarioUno = {
nombre:'Asabeneh',
papel:'teaching',
pais:'Finland'
}
let userTwo = userOne
console.log(usuarioUno == usuarioDos) // Verdadero
```
Si tiene dificultades comprendiendo la diferencia entre los tipos de datos primitivos y los tipos de datos no primitivos, no es el único. Cálmate y ve a la siguiente sección e intenta volver después de un tiempo. Ahora comencemos los tipos de datos por tipo de número.
## Números
Los números son números enteros y valores decimales que pueden hacer todas las operaciones aritméticas.
Veamos algunos ejemplos de Números.
### Declaración de tipos de datos numéricos
```js
let edad = 35
const gravedad = 9.81 // usamos const para valores que no cambian, constante gravitacional en m/s2
let masa = 72 // masa en Kilogramo
const PI = 3.14 // pi una constante geométrica
// Más ejemplos
const boilingPoint = 100 // temperatura en oC, punto de ebullición del agua que es una constante
const bodyTemp = 37 // oC la temperatura corporal promedio del ser humano, que es una constante
console.log(edad, gravedad, masa, PI, boilingPoint, bodyTemp)
```
### Objeto matemático
En JavaScript, el objeto matemático proporciona muchos métodos para trabajar con números.
```js
const PI = Math.PI
console.log(PI) // 3.141592653589793
// Redondeo al número más cercano
// si es superior a 0,5 hacia arriba si es inferior a 0,5 redondeo hacia abajo
console.log(Math.round(PI)) // 3 para redondear valores al número más cercano
console.log(Math.round(9.81)) // 10
console.log(Math.floor(PI)) // 3 redondeando hacia abajo
console.log(Math.ceil(PI)) // 4 redondeando hacia arriba
console.log(Math.min(-5, 3, 20, 4, 5, 10)) // -5, devuelve el valor mínimo
console.log(Math.max(-5, 3, 20, 4, 5, 10)) // 20, devuelve el valor máximo
const randNum = Math.random() // crea un número aleatorio entre 0 y 0,999999
console.log(randNum)
// Vamos a crear un número aleatorio entre 0 y 10
const num = Math.floor(Math.random () * 11) // crea un número aleatorio entre 0 y 10
console.log(num)
//Valor absoluto
console.log(Math.abs(-10)) // 10
//Raíz cuadrada
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) // 1.4142135623730951
// Poder
console.log(Math.pow(3, 2)) // 9
console.log(Math.E) // 2.718
// Logaritmo
// Devuelve el logaritmo natural con base E de x, Math.log(x)
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
// Devuelve el logaritmo natural de 2 y 10 respectivamente
console.log(Math.LN2) // 0.6931471805599453
console.log(Math.LN10) // 2.302585092994046
// Trigonometría
Math.sin(0)
Math.sin(60)
Math.cos(0)
Math.cos(60)
```
#### Generador de números aleatorios
El objeto matemático de JavaScript tiene un generador de números de método random() que genera un número de 0 a 0.999999999...
```js
let randomNum = Math.random() // genera 0 a 0.999...
```
Ahora, veamos cómo podemos usar el método random() para generar un número aleatorio entre 0 y 10:
```js
let randomNum = Math.random() // 0 a 0.999
let numBtnZeroAndTen = randomNum * 11
console.log(numBtnZeroAndTen) // esto da: min 0 y max 10.99
let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen)
console.log(randomNumRoundToFloor) // esto da entre 0 y 10
```
## Cadenas
Las cadenas son textos, que están debajo de **_single_** , **_double_**, **_back-tick_** comillas. Para declarar una cadena, necesitamos un nombre de variable, un operador de asignación, un valor entre comillas simples, comillas dobles o comillas invertidas.
Veamos algunos ejemplos de cadenas:
```js
let espacio = ' ' // una cadena de espacio vacío
let primerNombre = 'Asabeneh'
let apellido = 'Yetayeh'
let pais = 'Finland'
let ciudad = 'Helsinki'
let idioma = 'JavaScript'
let trabajo = 'teacher'
let cita = "The saying,'Seeing is Believing' is not correct in 2020."
let quotConBackTick = `The saying,'Seeing is Believing' is not correct in 2020.`
```
### Concatenación de cadenas
La conexión de dos o más cadenas entre sí se llama concatenación.
Usando las cadenas declaradas en la sección de Cadenas anterior:
```js
let nombreCompleto = primerNombre + espacio + apellido; // concatenación, fusionando dos cadenas juntas.
console.log(nombreCompleto);
```
```sh
Asabeneh Yetayeh
```
Podemos concatenar cadenas de diferentes formas.
#### Concatenar usando el operador de suma
Concatenar usando el operador de suma es una forma antigua. Esta forma de concatenar es tediosa y propensa a errores. Es bueno saber cómo concatenar de esta manera, pero recomiendo enfáticamente usar las cadenas de plantilla ES6 (explicadas más adelante).
```js
// Declarar diferentes variables de diferentes tipos de datos
let espacio = ' '
let primerNombre = 'Asabeneh'
let apellido = 'Yetayeh'
let pais = 'Finland'
let ciudad = 'Helsinki'
let idioma = 'JavaScript'
let trabajo = 'teacher'
let edad = 250
let nombreCompleto = primerNombre + espacio + apellido;
let datosPersonaUno = nombreCompleto + '. Yo tengo ' + edad + '. Vivo en' + pais; // Adición de cadena ES5
console.log(personInfoOne)
```
```sh
Asabeneh Yetayeh. Yo tengo 250v Finland
```
#### Cadenas literales largas
Una cadena puede ser un solo carácter, un párrafo o una página. Si la longitud de la cadena es demasiado grande, no cabe en una línea. Podemos usar el carácter de barra invertida (\\) al final de cada línea para indicar que la cadena continuará en la línea siguiente.
**Ejemplo:**
```js
const parrafo = "Mi nombre es Asabeneh Yetayeh. Vivo en Finlandia, Helsinki.\
Soy profesora y me encanta enseñar. Enseño HTML, CSS, JavaScript, React, Redux, \
Node.js, Python, Data Analysis y D3.js para cualquier persona interesada en aprender. \
A fines de 2019, estaba pensando en expandir mi enseñanza y llegar a \
a la audiencia global y comencé un desafío de Python del 20 de noviembre al 19 de diciembre.\
Fue una de las experiencias más gratificantes e inspiradoras.\
Ahora, estamos en 2020. Disfruto preparando el desafío 30DaysOfJavaScript y \
Espero que tú también estés disfrutando."
console.log(parrafo)
```
#### Secuencias de escape en cadenas
En JavaScript y otros lenguajes de programación \ seguido de algunos caracteres es una secuencia de escape. Veamos los caracteres de escape más comunes:
-\n: nueva linea
- \t: Tabulador, significa 8 espacios
- \\\\: barra invertida
- \\': Una frase (')
- \\": comillas dobles (")
```js
console.log('Espero que todos estén disfrutando el desafío de 30 días de JavaScript.\¿Y tú?') // salto de línea
console.log('Días\temas\Ejercicios')
console.log('Día 1\t3\t5')
console.log('Día 2\t3\t5')
console.log('Día 3\t3\t5')
console.log('Día 4\t3\t5')
console.log('Este es un símbolo de barra invertida (\\)') // Para escribir una barra invertida
console.log('En todos los lenguajes de programación comienza con \"¡Hola, mundo!\"')
console.log("En todos los lenguajes de programación comienza con \'¡Hola, mundo!\'")
console.log('El dicho \'Ver para creer\' no es correcto en 2022')
```
Salida en consola:
```sh
Espero que todos estén disfrutando el desafío de 30 días de JavaScript.
¿Y tú?
Días temas Ejercicios
Día 1 3 5
Día 2 3 5
Día 3 3 5
Día 4 3 5
Este es un símbolo de barra invertida (\)
En todos los lenguajes de programación comienza con"¡Hola, mundo!"
En todos los lenguajes de programación comienza con"¡Hola, mundo!"
El dicho 'Ver para creer' no es correcto en 2022
```
#### Literales de plantilla
Para crear una plantilla de cadenas(cadenas de plantilla), usamos dos tildes de retroceso. Podemos inyectar datos como expresiones dentro de una cadena de plantilla. Para inyectar datos, encerramos la expresión con un corchete ({}) precedido por un signo $. Consulte la sintaxis a continuación.
```js
//Sintaxis
`Texto literal de cadena`
`Cadena de texto literal ${expresión}`
```
**Ejemplo: 1**
```js
console.log(`La suma de 2 y 3 es 5`) // escribiendo estáticamente los datos
let a = 2
let b = 3
console.log(`La suma de ${a} y ${b} es ${a + b}`) // inyectando los datos dinámicamente
```
**Ejemplo:2**
```js
let espacio = ' '
let primerNombre = 'Asabeneh'
let apellido = 'Yetayeh'
let pais = 'Finland'
let ciudad = 'Helsinki'
let idioma = 'JavaScript'
let trabajo = 'profesora'
let edad = 250
let nombreCompleto = primerNombre + espacio + apellido;
let personaInfoDos = `Soy ${nombreCompleto}. Tengo ${edad} años. Vivo en ${pais}.` //ES6 - Método de interpolación de cadenas
let personaInfoTres = `Soy ${nombreCompleto}. Vivo en ${ciudad}, ${pais}. Soy una ${trabajo}. Enseño ${idioma}.`
console.log(personaInfoDos)
console.log(personaInfoTres)
```
```sh
Soy Asabeneh Yetayeh. Tengo 250 años. Vivo en in Finland.
Soy Asabeneh Yetayeh. Vivo en Helsinki, Finland. Soy una profesora. Enseño JavaScript.
```
Usando una plantilla de cadena o un método de interpolación de cadena, podemos agregar expresiones, que podrían ser un valor, o algunas operaciones (comparación, operaciones aritméticas, operación ternaria).
```js
let a = 2
let b = 3
console.log(`${a} es mayor que ${b}: ${a > b}`)
```
```sh
2 es mayor que 3: false
```
### Métodos de cadena
Todo en JavaScript es un objeto. Una cadena es un tipo de datos primitivo, lo que significa que no podemos modificarla una vez que se crea. El objeto de cadena tiene muchos métodos de cadena. Existen diferentes métodos de cadenas que nos pueden ayudar a trabajar con cadenas.
1. *longitud*: el método de cadena *longitud* devuelve el número de caracteres en una cadena incluido el espacio vacío.
**Example:**
```js
let js = 'JavaScript'
console.log(js.length) // 10
let primerNombre = 'Asabeneh'
console.log(primerNombre.length) // 8
```
2. *Acceder a los caracteres de una cadena*: Podemos acceder a cada carácter de una cadena usando su índice. En programación, el conteo comienza desde 0. El primer índice de la cadena es cero y el último índice es la longitud de la cadena menos uno.
![Accessing sting by index](../images/string_indexes.png)
Accedamos a diferentes caracteres en la cadena 'JavaScript'.
```js
let string = 'JavaScript'
let firstLetter = string[0]
console.log(firstLetter) // J
let secondLetter = string[1] // a
let thirdLetter = string[2]
let lastLetter = string[9]
console.log(lastLetter) // t
let lastIndex = string.length - 1
console.log(lastIndex) // 9
console.log(string[lastIndex]) // t
```
3. *toUpperCase()*: este método cambia la cadena a letras mayúsculas.
```js
let string = 'JavaScript'
console.log(string.toUpperCase()) // JAVASCRIPT
let firstName = 'Asabeneh'
console.log(firstName.toUpperCase()) // ASABENEH
let country = 'Finland'
console.log(country.toUpperCase()) // FINLAND
```
4. *toLowerCase()*: este método cambia la cadena a letras minúsculas.
```js
let string = 'JavasCript'
console.log(string.toLowerCase()) // javascript
let firstName = 'Asabeneh'
console.log(firstName.toLowerCase()) // asabeneh
let country = 'Finland'
console.log(country.toLowerCase()) // finland
```
5. *substr()*: Se necesitan dos argumentos, el índice inicial y el número de caracteres para dividir.
```js
let string = 'JavaScript'
console.log(string.substr(4,6)) // Script
let country = 'Finland'
console.log(country.substr(3, 4)) // land
```
6. *substring()*: Toma dos argumentos, el índice inicial y el índice final, pero no incluye el carácter en el índice final.
```js
let string = 'JavaScript'
console.log(string.substring(0,4)) // Java
console.log(string.substring(4,10)) // Script
console.log(string.substring(4)) // Script
let country = 'Finland'
console.log(country.substring(0, 3)) // Fin
console.log(country.substring(3, 7)) // land
console.log(country.substring(3)) // land
```
7. *split()*: El método split divide una cadena en un lugar específico.
```js
let string = '30 Days Of JavaScript'
console.log(string.split()) // Cambios en una matriz -> ["30 Days Of JavaScript"]
console.log(string.split(' ')) // Dividir a una matriz en el espacio -> ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh'
console.log(firstName.split()) // Cambiar a una matriz - > ["Asabeneh"]
console.log(firstName.split('')) // Dividir en una matriz en cada letra -> ["A", "s", "a", "b", "e", "n", "e", "h"]
let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(countries.split(',')) // Dividir en cualquier matriz en coma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
```
8. *trim()*: Elimina el espacio final al principio o al final de una cadena.
```js
let string = ' 30 Days Of JavaScript '
console.log(string)
console.log(string.trim(' '))
let firstName = ' Asabeneh '
console.log(firstName)
console.log(firstName.trim()) // todavía elimina espacios al principio y al final de la cadena
```
```sh
30 Days Of JavasCript
30 Days Of JavasCript
Asabeneh
Asabeneh
```
9. *includes()*: Toma un argumento de subcadena y verifica si existe un argumento de subcadena en la cadena. *includes()* devuelve un valor booleano. Si existe una subcadena en una cadena, devuelve verdadero; de lo contrario, devuelve falso.
```js
let string = '30 Days Of JavaScript'
console.log(string.includes('Days')) // verdadero
console.log(string.includes('days')) // falso: ¡se distingue entre mayúsculas y minúsculas!
console.log(string.includes('Script')) // verdadero
console.log(string.includes('script')) // falso
console.log(string.includes('java')) // falso
console.log(string.includes('Java')) // verdadero
let country = 'Finland'
console.log(country.includes('fin')) // falso
console.log(country.includes('Fin')) // verdadero
console.log(country.includes('land')) // verdadero
console.log(country.includes('Land')) // falso
```
10. *replace()*: toma como parámetro la subcadena antigua y una nueva subcadena.
```js
string.replace(oldsubstring, newsubstring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
let country = 'Finland'
console.log(country.replace('Fin', 'Noman')) // Nomanland
```
11. *charAt()*: Toma índice y devuelve el valor en ese índice
```js
string.charAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charAt(0)) // 3
let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)) // t
```
12. *charCodeAt()*: Toma el índice y devuelve el código char (número ASCII) del valor en ese índice
```js
string.charCodeAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charCodeAt(3)) // D ASCII numbero es 68
let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)) // t ASCII es 116
```
13. *indexOf()*: Toma una subcadena y si la subcadena existe en una cadena, devuelve la primera posición de la subcadena; si no existe, devuelve -1
```js
string.indexOf(substring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.indexOf('D')) // 3
console.log(string.indexOf('Days')) // 3
console.log(string.indexOf('days')) // -1
console.log(string.indexOf('a')) // 4
console.log(string.indexOf('JavaScript')) // 11
console.log(string.indexOf('Script')) //15
console.log(string.indexOf('script')) // -1
```
14. *lastIndexOf()*: Toma una subcadena y si la subcadena existe en una cadena, devuelve la última posición de la subcadena; si no existe, devuelve -1
```js
//syntax
string.lastIndexOf(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.lastIndexOf('love')) // 67
console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38
```
15. *concat()*: toma muchas subcadenas y las une.
```js
string.concat(substring, substring, substring)
```
```js
let string = '30'
console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript
let country = 'Fin'
console.log(country.concat("land")) // Finland
```
16. *startsWith*: toma una subcadena como argumento y verifica si la cadena comienza con esa subcadena especificada. Devuelve un valor booleano (verdadero o falso).
```js
//syntax
string.startsWith(substring)
```
```js
let string = 'Love is the best to in this world'
console.log(string.startsWith('Love')) // verdadero
console.log(string.startsWith('love')) // falso
console.log(string.startsWith('world')) // falso
let country = 'Finland'
console.log(country.startsWith('Fin')) // verdadero
console.log(country.startsWith('fin')) // falso
console.log(country.startsWith('land')) // falso
```
17. *endsWith*: toma una subcadena como argumento y verifica si la cadena termina con esa subcadena especificada. Devuelve un valor booleano (verdadero o falso).
```js
string.endsWith(substring)
```
```js
let string = 'Love is the most powerful feeling in the world'
console.log(string.endsWith('world')) // verdadero
console.log(string.endsWith('love')) // falso
console.log(string.endsWith('in the world')) // verdadero
let country = 'Finland'
console.log(country.endsWith('land')) // verdadero
console.log(country.endsWith('fin')) // falso
console.log(country.endsWith('Fin')) // falso
```
18. *search*: toma una subcadena como argumento y devuelve el índice de la primera coincidencia. El valor de búsqueda puede ser una cadena o un patrón de expresión regular.
```js
string.search(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2
console.log(string.search(/javascript/gi)) // 7
```
19. *match*: toma una subcadena o un patrón de expresión regular como argumento y devuelve una matriz si hay una coincidencia; de lo contrario, devuelve un valor nulo. Veamos cómo se ve un patrón de expresión regular. Comienza con /signo y termina con /signo.
```js
let string = 'love'
let patternOne = /love/ // sin ninguna bandera
let patternTwo = /love/gi // g-significa buscar en todo el texto, i - no distingue entre mayúsculas y minúsculas
```
Coincidencia de sintaxis
```js
// sintaxis
string.match(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.match('love'))
```
```sh
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
```
```js
let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
```
Extraigamos números del texto usando una expresión regular. Esta no es la sección de expresiones regulares, ¡no se asuste! Cubriremos las expresiones regulares más adelante.
```js
let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge'
let regEx = /\d+/
// d con carácter de escape significa que d no es una d normal sino que actúa como un dígito
// + significa uno o más dígitos,
// si hay g después de eso, significa global, busque en todas partes.
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
```
20. *repeat()*: toma un número como argumento y devuelve la versión repetida de la cadena.
```js
string.repeat(n)
```
```js
let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
```
## Comprobación de tipos de datos y conversión
### Comprobación de tipos de datos
Para comprobar el tipo de datos de una determinada variable utilizamos el método _typeof_.
**Ejemplo:**
```js
// Diferentes tipos de datos javascript
// Declaremos diferentes tipos de datos
let firstName = 'Asabeneh' // cadena
let lastName = 'Yetayeh' // cadena
let pais = 'Finlandia'. // cadena
let ciudad = 'Helsinki' // cadena
let edad = 250 // numero, no es mi edad real, no te preocupes
let trabajo // indefinido, porque no se asignó un valor
console.log(typeof 'Asabeneh') // cadena
console.log(typeof firstName) // cadena
console.log(typeof 10) // numbero
console.log(typeof 3.14) // numbero
console.log(typeof true) // booleano
console.log(typeof false) // booleano
console.log(typeof NaN) // numbero
console.log(typeof job) // indefinido
console.log(typeof undefined) // indefinido
console.log(typeof null) // objeto
```
### Cambio del tipo de datos
- Casting: Conversión de un tipo de datos a otro tipo de datos. Usamos _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_
Cuando hacemos operaciones aritméticas, los números de cadena deben convertirse primero en enteros o flotantes; de lo contrario, devuelve un error.
#### Cadena a Int
Podemos convertir el número de cadena en un número. Cualquier número dentro de una comilla es un número de cadena. Un ejemplo de un número de cadena: '10', '5', etc.
Podemos convertir cadena a número usando los siguientes métodos:
- parseInt()
- Número()
- Signo más (+)
```js
let num = '10'
let numInt = parseInt(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = Number(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = +num
console.log(numInt) // 10
```
#### Cadena a Floatante
Podemos convertir un número flotante de cadena en un número flotante. Cualquier número flotante dentro de una comilla es un número flotante de cadena. Un ejemplo de un número flotante de cadena: '9.81', '3.14', '1.44', etc.
Podemos convertir cadenas flotantes en números usando los siguientes métodos:
- parseFloat()
- Número()
- Signo más (+)
```js
let num = '9.81'
let numFloat = parseFloat(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = Number(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = +num
console.log(numFloat) // 9.81
```
#### Flotante a Int
Podemos convertir números flotantes a enteros.
Usamos el siguiente método para convertir float a int:
- parseInt()
```js
let num = 9.81
let numInt = parseInt(num)
console.log(numInt) // 9
```
🌕 Usted es maravilloso. Acabas de completar los desafíos del día 2 y estás dos pasos adelante en tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos.
## 💻 Día 2: Ejercicios
### Ejercicio: Nivel 1
1. Declare una variable llamada desafío y asígnele un valor inicial **'30 días de JavaScript'**.
2. Imprima la cadena en la consola del navegador usando __console.log()__
3. Imprima la __longitud__ de la cadena en la consola del navegador usando _console.log()_
4. Cambie todos los caracteres de cadena a letras mayúsculas usando el método __toUpperCase()__
5. Cambie todos los caracteres de la cadena a letras minúsculas usando el método __toLowerCase()__
6. Corta (segmenta) la primera palabra de la cadena usando el método __substr()__ o __substring()__
7. Corta la frase *Days Of JavaScript* de *30 Days Of JavaScript*.
8. Verifique si la cadena contiene una palabra __Script__ usando el método __includes()__
9. Divide la __cadena__ en un __array__ usando el método __split()__
10. Divida la cadena 30 días de JavaScript en el espacio usando el método __split()__
11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __divide__ la cadena en la coma y cámbiala a una matriz.
12. Cambie 30 días de JavaScript a 30 días de Python usando el método __replace()__.
13. ¿Qué es el carácter en el índice 15 en la cadena '30 días de JavaScript'? Utilice el método __charAt()__.
14. ¿Cuál es el código de carácter de J en la cadena '30 días de JavaScript' usando __charCodeAt()__
15. Use __indexOf__ para determinar la posición de la primera aparición de __a__ en 30 días de JavaScript
16. Utilice __lastIndexOf__ para determinar la posición de la última aparición de __a__ en 30 días de JavaScript.
17. Usa __indexOf__ para encontrar la posición de la primera aparición de la palabra __porque__ en la siguiente oración:__'No puedes terminar una oración con porque porque porque es una conjunción'__
18. Usa __lastIndexOf__ para encontrar la posición de la última aparición de la palabra __porque__ en la siguiente oración:__'No puedes terminar una oración con porque porque porque es una conjunción'__
19. Usa __buscar__ para encontrar la posición de la primera aparición de la palabra __porque__ en la siguiente oración:__'No puedes terminar una oración con porque porque porque es una conjunción'__
20. Use __trim()__ para eliminar cualquier espacio en blanco final al principio y al final de una cadena. Por ejemplo, '30 días de JavaScript'.
21. Use el método __startsWith()__ con la cadena *30 días de JavaScript* y haga que el resultado sea verdadero
22. Use el método __endsWith()__ con la cadena *30 días de JavaScript* y haga que el resultado sea verdadero
23. Usa el método __match()__ para encontrar todos los __a__ en 30 días de JavaScript
24. Use __concat()__ y fusione '30 días de' y 'JavaScript' en una sola cadena, '30 días de JavaScript'
25. Use el método __repeat()__ para imprimir 30 días de JavaScript 2 veces
### Ejercicio: Nivel 2
1. Usando console.log() imprima la siguiente declaración:
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help one another.
```
2. Usando console.log() imprima la siguiente cita de la Madre Teresa:
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
3. Compruebe si typeof '10' es exactamente igual a 10. Si no, hágalo exactamente igual.
4. Compruebe si parseFloat('9.8') es igual a 10, si no, hágalo exactamente igual a 10.
5. Verifique si 'on' se encuentra tanto en Python como en la jerga
6. _Espero que este curso no esté lleno de jerga_. Compruebe si _jargon_ está en la oración.
7. Genere un número aleatorio entre 0 y 100 inclusive.
8. Genere un número aleatorio entre 50 y 100 inclusive.
9. Genere un número aleatorio entre 0 y 255 inclusive.
10. Acceda a los caracteres de la cadena 'JavaScript' utilizando un número aleatorio.
11. Use console.log() y caracteres de escape para imprimir el siguiente patrón.
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
12. Usa __substr__ para separar la frase __porque porque porque__ de la siguiente oración:__'No puedes terminar una oración con porque porque porque es una conjunción'__
### Ejercicios: Nivel 3
1. 'El amor es lo mejor que hay en este mundo. Algunos encontraron su amor y algunos todavía están buscando su amor. Cuente el número de palabras __amor__ en esta oración.
2. Usa __match()__ para contar el número de todos los __porque__ en la siguiente oración:__'No puedes terminar una oración con porque porque porque es una conjunción'__
3. Limpia el siguiente texto y encuentra la palabra más frecuente (pista, usa replace y expresiones regulares).
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching'
```
4. Calcula el ingreso anual total de la persona extrayendo los números del siguiente texto. 'Él gana 5000 euros de salario por mes, bono anual de 10000 euros, cursos en línea de 15000 euros por mes.'
🎉 ¡FELICITACIONES! 🎉
[<< Día 1](../readMe.md) |

@ -70,6 +70,7 @@
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ó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
Ningún conocimiento previo es requerido para el siguiente desafío. Solo necesitarás:
@ -101,7 +102,7 @@ Puedes comprobar si se ha instalado correctamente abriendo la terminal del orden
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
@ -389,8 +390,8 @@ Recuerda que los números decimales se deben separar por un punto, no vale usar
Una colección de uno o más carácteres entre comillas. **Ejemplo:**
"Asabeneh
"Finlandia
"Asabeneh"
"Finlandia"
'JavaScript es un hermoso lenguaje de programación'.
"Me encanta enseñar"
"Espero que estés disfrutando del primer día"

@ -0,0 +1,980 @@
<div align="center">
<h1> Học JavaScript trong 30 ngày: Kiểu dữ liệu</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Tác giả:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Tháng 1, 2020</small>
</sub>
</div>
</div>
[<< Ngày 1](../README.md) | [Ngày 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)
![Ngày thứ hai học JavaScript](../../images/banners/day_1_2.png)
- [📔 Ngày 2](#-day-2)
- [Kiểu dữ liệu](#data-types)
- [Kiểu dữ liệu nguyên thuỷ](#primitive-data-types)
- [Kiểu dữ liệu không nguyên thủy](#non-primitive-data-types)
- [Numbers](#numbers)
- [Khai báo kiểu dữ liệu Number](#declaring-number-data-types)
- [Đối tượng math](#math-object)
- [Tạo số ngẫu nhiên](#random-number-generator)
- [Strings](#strings)
- [Nối chuỗi](#string-concatenation)
- [Nối chuỗi bằng toán tử cộng](#concatenating-using-addition-operator)
- [Chuỗi dài](#long-literal-strings)
- [Chuỗi thoát trong Strings](#escape-sequences-in-strings)
- [Template Literals (Template Strings)](#template-literals-template-strings)
- [Phương thức chuỗi](#string-methods)
- [Xác định kiểu dữ liệu và truyền](#checking-data-types-and-casting)
- [Kiểm tra kiểu dữ liệu](#checking-data-types)
- [Thay đổi kiểu dữ liệu (Truyền)](#changing-data-type-casting)
- [String thành Int](#string-to-int)
- [String thành Float](#string-to-float)
- [Float thành Int](#float-to-int)
- [💻 Day 2: Bài tập](#-day-2-exercises)
- [Bài tập: Cấp độ 1](#exercise-level-1)
- [Bài tập: Cấp độ 2](#exercise-level-2)
- [Bài tập: Cấp độ 3](#exercises-level-3)
# 📔 Ngày 2
## Kiểu dữ liệu
In the previous section, we mentioned a little bit about data types. Data or values have data types. Data types describe the characteristics of data. Data types can be divided into two:
1. Primitive data types
2. Non-primitive data types(Object References)
### Kiểu dữ liệu nguyên thuỷ
Primitive data types in JavaScript include:
1. Numbers - Integers, floats
2. Strings - Any data under single quote, double quote or backtick quote
3. Booleans - true or false value
4. Null - empty value or no value
5. Undefined - a declared variable without a value
Non-primitive data types in JavaScript includes:
1. Objects
2. Functions
3. Arrays
Now, let us see what exactly primitive and non-primitive data types mean.
*Primitive* data types are immutable(non-modifiable) data types. Once a primitive data type is created we cannot modify it.
**Example:**
```js
let word = 'JavaScript'
```
If we try to modify the string stored in variable *word*, JavaScript should raise an error. Any data type under a single quote, double quote, or backtick quote is a string data type.
```js
word[0] = 'Y'
```
This expression does not change the string stored in the variable *word*. So, we can say that strings are not modifiable or in other words immutable.
Primitive data types are compared by its values. Let us compare different data values. See the example below:
```js
let numOne = 3
let numTwo = 3
console.log(numOne == numTwo) // true
let js = 'JavaScript'
let py = 'Python'
console.log(js == py) //false
let lightOn = true
let lightOff = false
console.log(lightOn == lightOff) // false
```
### Kiểu dữ liệu không nguyên thuỷ
*Non-primitive* data types are modifiable or mutable. We can modify the value of non-primitive data types after it gets created.
Let us see by creating an array. An array is a list of data values in a square bracket. Arrays can contain the same or different data types. Array values are referenced by their index. In JavaScript array index starts at zero. I.e., the first element of an array is found at index zero, the second element at index one, and the third element at index two, etc.
```js
let nums = [1, 2, 3]
nums[0] = 10
console.log(nums) // [10, 2, 3]
```
As you can see, an array, which is a non-primitive data type is mutable. Non-primitive data types cannot be compared by value. Even if two non-primitive data types have the same properties and values, they are not strictly equal.
```js
let nums = [1, 2, 3]
let numbers = [1, 2, 3]
console.log(nums == numbers) // false
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
let userTwo = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
console.log(userOne == userTwo) // false
```
Rule of thumb, we do not compare non-primitive data types. Do not compare arrays, functions, or objects.
Non-primitive values are referred to as reference types, because they are being compared by reference instead of value. Two objects are only strictly equal if they refer to the same underlying object.
```js
let nums = [1, 2, 3]
let numbers = nums
console.log(nums == numbers) // true
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
let userTwo = userOne
console.log(userOne == userTwo) // true
```
If you have a hard time understanding the difference between primitive data types and non-primitive data types, you are not the only one. Calm down and just go to the next section and try to come back after some time. Now let us start the data types by number type.
## Numbers
Numbers are integers and decimal values which can do all the arithmetic operations.
Let's see some examples of Numbers.
### Declaring Number Data Types
```js
let age = 35
const gravity = 9.81 // we use const for non-changing values, gravitational constant in m/s2
let mass = 72 // mass in Kilogram
const PI = 3.14 // pi a geometrical constant
// More Examples
const boilingPoint = 100 // temperature in oC, boiling point of water which is a constant
const bodyTemp = 37 // oC average human body temperature, which is a constant
console.log(age, gravity, mass, PI, boilingPoint, bodyTemp)
```
### Đối tượng Math
In JavaScript the Math Object provides a lots of methods to work with numbers.
```js
const PI = Math.PI
console.log(PI) // 3.141592653589793
// Rounding to the closest number
// if above .5 up if less 0.5 down rounding
console.log(Math.round(PI)) // 3 to round values to the nearest number
console.log(Math.round(9.81)) // 10
console.log(Math.floor(PI)) // 3 rounding down
console.log(Math.ceil(PI)) // 4 rounding up
console.log(Math.min(-5, 3, 20, 4, 5, 10)) // -5, returns the minimum value
console.log(Math.max(-5, 3, 20, 4, 5, 10)) // 20, returns the maximum value
const randNum = Math.random() // creates random number between 0 to 0.999999
console.log(randNum)
// Let us create random number between 0 to 10
const num = Math.floor(Math.random () * 11) // creates random number between 0 and 10
console.log(num)
//Absolute value
console.log(Math.abs(-10)) // 10
//Square root
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) // 1.4142135623730951
// Power
console.log(Math.pow(3, 2)) // 9
console.log(Math.E) // 2.718
// Logarithm
// Returns the natural logarithm with base E of x, Math.log(x)
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
// Returns the natural logarithm of 2 and 10 respectively
console.log(Math.LN2) // 0.6931471805599453
console.log(Math.LN10) // 2.302585092994046
// Trigonometry
Math.sin(0)
Math.sin(60)
Math.cos(0)
Math.cos(60)
```
#### Tạo số ngẫu nhiên
The JavaScript Math Object has a random() method number generator which generates number from 0 to 0.999999999...
```js
let randomNum = Math.random() // generates 0 to 0.999...
```
Now, let us see how we can use random() method to generate a random number between 0 and 10:
```js
let randomNum = Math.random() // generates 0 to 0.999
let numBtnZeroAndTen = randomNum * 11
console.log(numBtnZeroAndTen) // this gives: min 0 and max 10.99
let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen)
console.log(randomNumRoundToFloor) // this gives between 0 and 10
```
## Strings
Strings are texts, which are under **_single_** , **_double_**, **_back-tick_** quote. To declare a string, we need a variable name, assignment operator, a value under a single quote, double quote, or backtick quote.
Let's see some examples of strings:
```js
let space = ' ' // chuỗi rỗng
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let quote = "The saying,'Seeing is Believing' is not correct in 2020."
let quotWithBackTick = `The saying,'Seeing is Believing' is not correct in 2020.`
```
### Nối chuỗi
Connecting two or more strings together is called concatenation.
Using the strings declared in the previous String section:
```js
let fullName = firstName + space + lastName; // concatenation, merging two string together.
console.log(fullName);
```
```sh
Asabeneh Yetayeh
```
We can concatenate strings in different ways.
#### Concatenating Using Addition Operator
Concatenating using the addition operator is an old way. This way of concatenating is tedious and error-prone. It is good to know how to concatenate this way, but I strongly suggest to use the ES6 template strings (explained later on).
```js
// Declaring different variables of different data types
let space = ' '
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let age = 250
let fullName =firstName + space + lastName
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country; // ES5 string addition
console.log(personInfoOne)
```
```sh
Asabeneh Yetayeh. I am 250. I live in Finland
```
#### Chuỗi dài
A string could be a single character or paragraph or a page. If the string length is too big it does not fit in one line. We can use the backslash character (\\) at the end of each line to indicate that the string will continue on the next line.
**Example:**
```js
const paragraph = "My name is Asabeneh Yetayeh. I live in Finland, Helsinki.\
I am a teacher and I love teaching. I teach HTML, CSS, JavaScript, React, Redux, \
Node.js, Python, Data Analysis and D3.js for anyone who is interested to learn. \
In the end of 2019, I was thinking to expand my teaching and to reach \
to global audience and I started a Python challenge from November 20 - December 19.\
It was one of the most rewarding and inspiring experience.\
Now, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \
I hope you are enjoying too."
console.log(paragraph)
```
#### Chuỗi thoát trong Strings
In JavaScript and other programming languages \ followed by some characters is an escape sequence. Let's see the most common escape characters:
- \n: new line
- \t: Tab, means 8 spaces
- \\\\: Back slash
- \\': Single quote (')
- \\": Double quote (")
```js
console.log('I hope everyone is enjoying the Học JavaScript trong 30 ngày challenge.\nDo you ?') // line break
console.log('Days\tTopics\tExercises')
console.log('Day 1\t3\t5')
console.log('Day 2\t3\t5')
console.log('Day 3\t3\t5')
console.log('Day 4\t3\t5')
console.log('This is a backslash symbol (\\)') // To write a backslash
console.log('In every programming language it starts with \"Hello, World!\"')
console.log("In every programming language it starts with \'Hello, World!\'")
console.log('The saying \'Seeing is Believing\' isn\'t correct in 2020')
```
Output in console:
```sh
I hope everyone is enjoying the Học JavaScript trong 30 ngày challenge.
Do you ?
Days Topics Exercises
Day 1 3 5
Day 2 3 5
Day 3 3 5
Day 4 3 5
This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
In every programming language it starts with 'Hello, World!'
The saying 'Seeing is Believing' isn't correct in 2020
```
#### Template Literals (Template Strings)
To create a template strings, we use two back-ticks. We can inject data as expressions inside a template string. To inject data, we enclose the expression with a curly bracket({}) preceded by a $ sign. See the syntax below.
```js
//Syntax
`String literal text`
`String literal text ${expression}`
```
**Ví dụ: 1**
```js
console.log(`The sum of 2 and 3 is 5`) // statically writing the data
let a = 2
let b = 3
console.log(`The sum of ${a} and ${b} is ${a + b}`) // injecting the data dynamically
```
**Ví dụ: 2**
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let age = 250
let fullName = firstName + ' ' + lastName
let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.` //ES6 - String interpolation method
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`
console.log(personInfoTwo)
console.log(personInfoThree)
```
```sh
I am Asabeneh Yetayeh. I am 250. I live in Finland.
I am Asabeneh Yetayeh. I live in Helsinki, Finland. I am a teacher. I teach JavaScript.
```
Using a string template or string interpolation method, we can add expressions, which could be a value, or some operations (comparison, arithmetic operations, ternary operation).
```js
let a = 2
let b = 3
console.log(`${a} is greater than ${b}: ${a > b}`)
```
```sh
2 is greater than 3: false
```
### Phương thức String
Everything in JavaScript is an object. A string is a primitive data type that means we can not modify it once it is created. The string object has many string methods. There are different string methods that can help us to work with strings.
1. *length*: The string *length* method returns the number of characters in a string included empty space.
**Example:**
```js
let js = 'JavaScript'
console.log(js.length) // 10
let firstName = 'Asabeneh'
console.log(firstName.length) // 8
```
2. *Accessing characters in a string*: We can access each character in a string using its index. In programming, counting starts from 0. The first index of the string is zero, and the last index is the length of the string minus one.
![Accessing sting by index](../../images/string_indexes.png)
Let us access different characters in 'JavaScript' string.
```js
let string = 'JavaScript'
let firstLetter = string[0]
console.log(firstLetter) // J
let secondLetter = string[1] // a
let thirdLetter = string[2]
let lastLetter = string[9]
console.log(lastLetter) // t
let lastIndex = string.length - 1
console.log(lastIndex) // 9
console.log(string[lastIndex]) // t
```
3. *toUpperCase()*: this method changes the string to uppercase letters.
```js
let string = 'JavaScript'
console.log(string.toUpperCase()) // JAVASCRIPT
let firstName = 'Asabeneh'
console.log(firstName.toUpperCase()) // ASABENEH
let country = 'Finland'
console.log(country.toUpperCase()) // FINLAND
```
4. *toLowerCase()*: this method changes the string to lowercase letters.
```js
let string = 'JavasCript'
console.log(string.toLowerCase()) // javascript
let firstName = 'Asabeneh'
console.log(firstName.toLowerCase()) // asabeneh
let country = 'Finland'
console.log(country.toLowerCase()) // finland
```
5. *substr()*: It takes two arguments, the starting index and number of characters to slice.
```js
let string = 'JavaScript'
console.log(string.substr(4,6)) // Script
let country = 'Finland'
console.log(country.substr(3, 4)) // land
```
6. *substring()*: It takes two arguments, the starting index and the stopping index but it doesn't include the character at the stopping index.
```js
let string = 'JavaScript'
console.log(string.substring(0,4)) // Java
console.log(string.substring(4,10)) // Script
console.log(string.substring(4)) // Script
let country = 'Finland'
console.log(country.substring(0, 3)) // Fin
console.log(country.substring(3, 7)) // land
console.log(country.substring(3)) // land
```
7. *split()*: The split method splits a string at a specified place.
```js
let string = 'Học JavaScript trong 30 ngày'
console.log(string.split()) // Changes to an array -> ["Học JavaScript trong 30 ngày"]
console.log(string.split(' ')) // Split to an array at space -> ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh'
console.log(firstName.split()) // Change to an array - > ["Asabeneh"]
console.log(firstName.split('')) // Split to an array at each letter -> ["A", "s", "a", "b", "e", "n", "e", "h"]
let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(countries.split(',')) // split to any array at comma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
```
8. *trim()*: Removes trailing space in the beginning or the end of a string.
```js
let string = ' Học JavaScript trong 30 ngày '
console.log(string)
console.log(string.trim(' '))
let firstName = ' Asabeneh '
console.log(firstName)
console.log(firstName.trim()) // still removes spaces at the beginning and the end of the string
```
```sh
Học JavaScript trong 30 ngày
Học JavaScript trong 30 ngày
Asabeneh
Asabeneh
```
9. *includes()*: It takes a substring argument and it checks if substring argument exists in the string. *includes()* returns a boolean. If a substring exist in a string, it returns true, otherwise it returns false.
```js
let string = 'Học JavaScript trong 30 ngày'
console.log(string.includes('Days')) // true
console.log(string.includes('days')) // false - it is case sensitive!
console.log(string.includes('Script')) // true
console.log(string.includes('script')) // false
console.log(string.includes('java')) // false
console.log(string.includes('Java')) // true
let country = 'Finland'
console.log(country.includes('fin')) // false
console.log(country.includes('Fin')) // true
console.log(country.includes('land')) // true
console.log(country.includes('Land')) // false
```
10. *replace()*: takes as a parameter the old substring and a new substring.
```js
string.replace(oldsubstring, newsubstring)
```
```js
let string = 'Học JavaScript trong 30 ngày'
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
let country = 'Finland'
console.log(country.replace('Fin', 'Noman')) // Nomanland
```
11. *charAt()*: Takes index and it returns the value at that index
```js
string.charAt(index)
```
```js
let string = 'Học JavaScript trong 30 ngày'
console.log(string.charAt(0)) // 3
let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)) // t
```
12. *charCodeAt()*: Takes index and it returns char code (ASCII number) of the value at that index
```js
string.charCodeAt(index)
```
```js
let string = 'Học JavaScript trong 30 ngày'
console.log(string.charCodeAt(3)) // D ASCII number is 68
let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)) // t ASCII is 116
```
13. *indexOf()*: Takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1
```js
string.indexOf(substring)
```
```js
let string = 'Học JavaScript trong 30 ngày'
console.log(string.indexOf('D')) // 3
console.log(string.indexOf('Days')) // 3
console.log(string.indexOf('days')) // -1
console.log(string.indexOf('a')) // 4
console.log(string.indexOf('JavaScript')) // 11
console.log(string.indexOf('Script')) //15
console.log(string.indexOf('script')) // -1
```
14. *lastIndexOf()*: Takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1
```js
//syntax
string.lastIndexOf(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.lastIndexOf('love')) // 67
console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38
```
15. *concat()*: it takes many substrings and joins them.
```js
string.concat(substring, substring, substring)
```
```js
let string = '30'
console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript
let country = 'Fin'
console.log(country.concat("land")) // Finland
```
16. *startsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
```js
//syntax
string.startsWith(substring)
```
```js
let string = 'Love is the best to in this world'
console.log(string.startsWith('Love')) // true
console.log(string.startsWith('love')) // false
console.log(string.startsWith('world')) // false
let country = 'Finland'
console.log(country.startsWith('Fin')) // true
console.log(country.startsWith('fin')) // false
console.log(country.startsWith('land')) // false
```
17. *endsWith*: it takes a substring as an argument and it checks if the string ends with that specified substring. It returns a boolean(true or false).
```js
string.endsWith(substring)
```
```js
let string = 'Love is the most powerful feeling in the world'
console.log(string.endsWith('world')) // true
console.log(string.endsWith('love')) // false
console.log(string.endsWith('in the world')) // true
let country = 'Finland'
console.log(country.endsWith('land')) // true
console.log(country.endsWith('fin')) // false
console.log(country.endsWith('Fin')) // false
```
18. *search*: it takes a substring as an argument and it returns the index of the first match. The search value can be a string or a regular expression pattern.
```js
string.search(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2
console.log(string.search(/javascript/gi)) // 7
```
19. *match*: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign.
```js
let string = 'love'
let patternOne = /love/ // with out any flag
let patternTwo = /love/gi // g-means to search in the whole text, i - case insensitive
```
Match syntax
```js
// syntax
string.match(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.match('love'))
```
```sh
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
```
```js
let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
```
Let us extract numbers from text using a regular expression. This is not the regular expression section, do not panic! We will cover regular expressions later on.
```js
let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge'
let regEx = /\d+/
// d with escape character means d not a normal d instead acts a digit
// + means one or more digit numbers,
// if there is g after that it means global, search everywhere.
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
```
20. *repeat()*: it takes a number as argument and it returns the repeated version of the string.
```js
string.repeat(n)
```
```js
let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
```
## Kiểm tra kiểu dữ liệu và Ép kiểu
### Kiểm tra kiểu dữ liệu
To check the data type of a certain variable we use the _typeof_ method.
**Example:**
```js
// Different javascript data types
// Let's declare different data types
let firstName = 'Asabeneh' // string
let lastName = 'Yetayeh' // string
let country = 'Finland' // string
let city = 'Helsinki' // string
let age = 250 // number, it is not my real age, do not worry about it
let job // undefined, because a value was not assigned
console.log(typeof 'Asabeneh') // string
console.log(typeof firstName) // string
console.log(typeof 10) // number
console.log(typeof 3.14) // number
console.log(typeof true) // boolean
console.log(typeof false) // boolean
console.log(typeof NaN) // number
console.log(typeof job) // undefined
console.log(typeof undefined) // undefined
console.log(typeof null) // object
```
### Đổi kiểu dữ liệu (Ép kiểu)
- Casting: Converting one data type to another data type. We use _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_
When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error.
#### String thành Int
We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: '10', '5', etc.
We can convert string to number using the following methods:
- parseInt()
- Number()
- Plus sign(+)
```js
let num = '10'
let numInt = parseInt(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = Number(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = +num
console.log(numInt) // 10
```
#### String thành Float
We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc.
We can convert string float to number using the following methods:
- parseFloat()
- Number()
- Plus sign(+)
```js
let num = '9.81'
let numFloat = parseFloat(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = Number(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = +num
console.log(numFloat) // 9.81
```
#### Float thành Int
We can convert float numbers to integers.
We use the following method to convert float to int:
- parseInt()
```js
let num = 9.81
let numInt = parseInt(num)
console.log(numInt) // 9
```
🌕 You are awesome. You have just completed day 2 challenges and you are two steps ahead on your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Ngày 2: Bài tập
### Bài tập: Cấp độ 1
1. Declare a variable named challenge and assign it to an initial value **'Học JavaScript trong 30 ngày'**.
2. Print the string on the browser console using __console.log()__
3. Print the __length__ of the string on the browser console using _console.log()_
4. Change all the string characters to capital letters using __toUpperCase()__ method
5. Change all the string characters to lowercase letters using __toLowerCase()__ method
6. Cut (slice) out the first word of the string using __substr()__ or __substring()__ method
7. Slice out the phrase *Days Of JavaScript* from *Học JavaScript trong 30 ngày*.
8. Check if the string contains a word __Script__ using __includes()__ method
9. Split the __string__ into an __array__ using __split()__ method
10. Split the string Học JavaScript trong 30 ngày at the space using __split()__ method
11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array.
12. Change Học JavaScript trong 30 ngày to 30 Days Of Python using __replace()__ method.
13. What is character at index 15 in 'Học JavaScript trong 30 ngày' string? Use __charAt()__ method.
14. What is the character code of J in 'Học JavaScript trong 30 ngày' string using __charCodeAt()__
15. Use __indexOf__ to determine the position of the first occurrence of __a__ in Học JavaScript trong 30 ngày
16. Use __lastIndexOf__ to determine the position of the last occurrence of __a__ in Học JavaScript trong 30 ngày.
17. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
18. Use __lastIndexOf__ to find the position of the last occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
19. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
20. Use __trim()__ to remove any trailing whitespace at the beginning and the end of a string.E.g ' Học JavaScript trong 30 ngày '.
21. Use __startsWith()__ method with the string *Học JavaScript trong 30 ngày* and make the result true
22. Use __endsWith()__ method with the string *Học JavaScript trong 30 ngày* and make the result true
23. Use __match()__ method to find all the __a__s in Học JavaScript trong 30 ngày
24. Use __concat()__ and merge '30 Days of' and 'JavaScript' to a single string, 'Học JavaScript trong 30 ngày'
25. Use __repeat()__ method to print Học JavaScript trong 30 ngày 2 times
### Bài tập: Cấp độ 2
1. Using console.log() print out the following statement:
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help one another.
```
2. Using console.log() print out the following quote by Mother Teresa:
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
3. Check if typeof '10' is exactly equal to 10. If not make it exactly equal.
4. Check if parseFloat('9.8') is equal to 10 if not make it exactly equal with 10.
5. Check if 'on' is found in both python and jargon
6. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence.
7. Generate a random number between 0 and 100 inclusively.
8. Generate a random number between 50 and 100 inclusively.
9. Generate a random number between 0 and 255 inclusively.
10. Access the 'JavaScript' string characters using a random number.
11. Use console.log() and escape characters to print the following pattern.
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
12. Use __substr__ to slice out the phrase __because because because__ from the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
### Bài tập: Cấp độ 3
1. 'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word __love__ in this sentence.
2. Use __match()__ to count the number of all __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
3. Clean the following text and find the most frequent word (hint, use replace and regular expressions).
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching'
```
4. Calculate the total annual income of the person by extracting the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'
🎉 CONGRATULATIONS ! 🎉
[<< Day 1](../readMe.md) | [Day 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)

@ -0,0 +1,669 @@
# Học JavaScript trong 30 ngày
| # Ngày | Phần |
| ----- | :-------------------------------------------------------------------------------------------------------------------------------------------------: |
| 01 | [Giới thiệu](./readMe.md) |
| 02 | [Kiểu dữ liệu](./02_Day_Data_types/02_day_data_types.md) |
| 03 | [Booleans, Toán tử, Date](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) |
| 04 | [Điều kiện](./04_Day_Conditionals/04_day_conditionals.md) |
| 05 | [Mảng](./05_Day_Arrays/05_day_arrays.md) |
| 06 | [Vòng lặp](./06_Day_Loops/06_day_loops.md) |
| 07 | [Functions](./07_Day_Functions/07_day_functions.md) |
| 08 | [Objects](./08_Day_Objects/08_day_objects.md) |
| 09 | [Đào sâu vào Functions](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) |
| 10 | [Sets và Maps](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) |
| 11 | [Destructuring và Spreading](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) |
| 12 | [Biểu thức chính quy](./12_Day_Regular_expressions/12_day_regular_expressions.md) |
| 13 | [Phương thức Console Object](./13_Day_Console_object_methods/13_day_console_object_methods.md) |
| 14 | [Error Handling](./14_Day_Error_handling/14_day_error_handling.md) |
| 15 | [Classes](./15_Day_Classes/15_day_classes.md) |
| 16 | [JSON](./16_Day_JSON/16_day_json.md) |
| 17 | [Web Storages](./17_Day_Web_storages/17_day_web_storages.md) |
| 18 | [Promises](./18_Day_Promises/18_day_promises.md) |
| 19 | [Closure](./19_Day_Closures/19_day_closures.md) |
| 20 | [Viết Clean Code](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) |
| 21 | [DOM](./21_Day_DOM/21_day_dom.md) |
| 22 | [Thao tác với DOM Object](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) |
| 23 | [Event Listeners](./23_Day_Event_listeners/23_day_event_listeners.md) |
| 24 | [Dự án nhỏ: Hệ mặt trời](./24_Day_Project_solar_system/24_day_project_solar_system.md) |
| 25 | [Dự án nhỏ: Hiển thị dữ liệu các quốc gia trên thế giới 1](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) |
| 26 | [Dự án nhỏ: Hiển thị dữ liệu các quốc gia trên thế giới 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) |
| 27 | [Dự án nhỏ: Portfolio](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) |
| 28 | [Dự án nhỏ: Bảng xếp hạng](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) |
| 29 | [Dự án nhỏ:Nhân vật hoạt hình](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) |
| 30 | [Dự án cuối cùng](./30_Day_Mini_project_final/30_day_mini_project_final.md) |
🧡🧡🧡 CHÚC BẠN CODE VUI VẺ 🧡🧡🧡
<div>
<small>Ủng hộ <strong>tác giả</strong> để bổ sung thêm nhiều kiến thức bổ ích</small> <br />
<a href="https://www.paypal.me/asabeneh">
<img src='../images/paypal_lg.png' alt='Paypal Logo' style="width:10%"/>
</a>
</div>
<div align="center">
<h1> Học JavaScript trong 30 ngày: Giới thiệu</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<br>
<sub>Tác giả:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Tháng 1, 2020</small>
</sub>
<div>
🇬🇧 [Tiếng Anh](./readMe.md)
🇪🇸 [Tiếng Tây Ban Nha](./Spanish/readme.md)
🇷🇺 [Tiếng Nga](./RU/README.md)
KR [Tiếng Hàn](./Korea/README.md)
</div>
</div>
</div>
[Ngày 2 >>](./02_Day_Data_types/02_day_data_types.md)
![Ngày thứ 2 học JavaScript](../images/day_1_1.png)
- [Học JavaScript trong 30 ngày](#30-days-of-javascript)
- [📔 Ngày 1](#-day-1)
- [Giới thiệu](#introduction)
- [Yêu cầu](#requirements)
- [Thiết lập](#setup)
- [Cài Node.js](#install-nodejs)
- [Trình duyệt](#browser)
- [Cài Google Chrome](#installing-google-chrome)
- [Mở Console Google Chrome](#opening-google-chrome-console)
- [Viết code trên Console trình duyệt](#writing-code-on-browser-console)
- [Console.log](#consolelog)
- [Console.log có nhiều tham số](#consolelog-with-multiple-arguments)
- [Comments](#comments)
- [Cú pháp](#syntax)
- [Toán tử](#arithmetics)
- [Code Editor](#code-editor)
- [Cài Visual Studio Code](#installing-visual-studio-code)
- [Cách sử dụng Visual Studio Code](#how-to-use-visual-studio-code)
- [Thêm JavaScript vào trang web](#adding-javascript-to-a-web-page)
- [Inline Script](#inline-script)
- [Internal Script](#internal-script)
- [External Script](#external-script)
- [Nhiều External Scripts](#multiple-external-scripts)
- [Giới thiệu về Kiểu dữ liệu](#introduction-to-data-types)
- [Numbers](#numbers)
- [Strings](#strings)
- [Booleans](#booleans)
- [Undefined](#undefined)
- [Null](#null)
- [Xác định kiểu dữ liệu](#checking-data-types)
- [Comments tiếp](#comments-again)
- [Biến](#variables)
- [💻 Ngày 1: Bài tập](#-day-1-exercises)
# 📔 Ngày 1
## Giới thiệu
**Chúc mừng bạn** đã quyết định tham gia học JavaScript trong 30 ngày. Trong thử thách này, bạn sẽ học mọi thứ bạn cần để trở thành một lập trình viên JavaScript, toàn bộ khái niệm về lập trình. Cuối thử thách, bạn sẽ nhận được chứng chỉ hoàn thành thử thách lập trình 30DaysOfJavaScript. Trong trường hợp bạn cần giúp đỡ hoặc nếu bạn muốn giúp đỡ người khác, bạn có thể tham gia [nhóm Telegram](https://t.me/ThirtyDaysOfJavaScript).
Thử thách **30DaysOfJavaScript** là để hướng dẫn cho cả người mới học và các lập trình viên JavaScript nâng cao. Chào bạn đến với JavaScript. JavaScript là ngôn ngữ lập trình của web. Tôi thích sử dụng và chia sẻ kiến thức về JavaScript và tôi hy vọng bạn cũng sẽ làm như vậy.
Trong các thử thách JavaScript này, bạn sẽ học JavaScript, ngôn ngữ lập trình phổ biến nhất thế giới đến thời điểm hiện tại.
JavaScript sử dụng để **_thêm tính tương tác cho các trang web, để phát triển ứng dụng di động, ứng dụng máy tính để bàn, trò chơi_** và ngày nay JavaScript có thể được sử dụng cho **_machine learning_** and **_AI_**.
**_JavaScript (JS)_** ngày càng phổ biến trong những năm gần đây và dẫn đầu các ngôn ngữ lập trình trong 6 năm liên tiếp và là ngôn ngữ lập trình được sử dụng nhiều nhất trên Github.
## Yêu cầu
Bạn không cần phải có kiến thức về lập trình để bắt đầu thử thách này, bạn chỉ cần có:
1. Động lực
2. Máy tính (Laptop)
3. Kết nối mạng
4. Trình duyệt
5. Code editor (VSCode)
## Thiết lập
Tôi tin rằng bạn có động lực và muốn trở thành một lập trình viên, máy tính và kết nối mạng. Nếu bạn đã có đầy đủ thì chúng ta hãy bắt đầu.
### Cài Node.js
Bạn có thể không cần phải cài Node.js ngay bây giờ nhưng sau này thì có thể cần đến. Cài [Node.js](https://nodejs.org/en/).
![Tải node](../images/download_node.png)
Sau khi tải xong, nhấn đúp để cài đặt
![Cài node](../images/install_node.png)
Chúng ta có thể kiểm tra xem Node đã cài hay chưa bằng cách mở terminal hoặc cmd trên máy tính.
```sh
$ node -v
v12.14.0
```
Khi làm bài hướng dẫn này tôi đang sử dụng phiên bản Node 12.14.0, nhưng hiện tại phiên bản Node.js được đề xuất để tải xuống là v17.6.0, bạn có thể sử dụng phiên bản Node mới nhất.
### Trình duyệt
Hiện tại có rất nhiều trình duyệt web, tuy nhiên tôi đề xuất nên sử dụng Google Chrome.
#### Cài Google Chrome
Cài [Google Chrome](https://www.google.com/chrome/) nếu bạn chưa cài nó. Chúng ta có thể viết code JavaScript trên console trình duyệt, nhưng chúng ta không sử dụng console trình duyệt để lập trình.
![Google Chrome](../images/google_chrome.png)
#### Mở Console Google Chrome
Bạn có thể mở console Google Chrome bằng cách nhấp vào ba dấu chấm ở trên cùng bên phải trình duyệt, chọn _More tools -> Developer tools_ hoặc sử dụng phím tắt.
![Mở chrome](../images/opening_developer_tool.png)
Để mở Console Google Chrome bằng phím tắt:
```sh
Mac
Command+Option+J
Windows/Linux:
Ctl+Shift+J (hoặc F12)
```
![Mở console](../images/opening_chrome_console_shortcut.png)
Sau khi bạn mở console Google Chrome, hãy thử khám phá các nút được đánh dấu bên dưới. Chúng ta sẽ dành phần lớn thời gian trên Console. Console là nơi bạn viết code JavaScript. Công cụ Google Console V8 sẽ chuyển code của bạn thành mã máy.
Bây giờ chúng ta sẽ viết mã JavaScript trên console của Google Chrome:
![viết code trên console](../images/js_code_on_chrome_console.png)
#### Viết code trên Console của trình duyệt
Chúng ta có thể viết bất kỳ code JavaScript nào trên console của Google hoặc bất kỳ console của trình duyệt nào. Tuy nhiên, đối với thử thách này, chúng ta chỉ sử dụng console của Google Chrome. Mở console bằng cách sử dụng:
```sh
Mac
Command+Option+I
Windows:
Ctl+Shift+I (hoặc F12)
```
##### Console.log
Để viết code JavaScript, chúng ta sẽ sử dụng 1 hàm có sẵn là **console.log()**. Chúng ta sẽ truyền vào một tham số và hàm sẽ hiển thị kết quả đã truyền vào. Chúng ta sẽ truyền `'Hello, World'` dưới dạng là tham số vào hàm `console.log()`.
```js
console.log('Hello, World!')
```
##### Console.log có nhiều tham số
Hàm **`console.log()`** có thể nhận nhiều tham số được phân cách bằng dấu phẩy. Cú pháp sẽ giống như này:**`console.log(param1, param2, param3)`**
![console log có nhiều tham số](../images/console_log_multipl_arguments.png)
```js
console.log('Hello', 'World', '!')
console.log('MỪNG', 'NGÀY', '8/3', 2022)
console.log('Chào bạn', 'đến với ', 30, 'Days', 'Of', 'JavaScript')
```
Bạn có thể thấy đoạn code bên trên, hàm _`console.log()`_ có thể nhận nhiều tham số.
Chúc mừng! Bạn đã viết code JavaScript bằng cách sử dụng _`console.log()`_.
##### Comments
Chúng ta có thể thêm comment vào code. Comment rất quan trọng để làm cho code dễ đọc hơn và để lại nhận xét trong code. JavaScript không chạy phần đã comment trong code. Trong JavaScript, bất kỳ dòng nào bắt đầu bằng `//` trong JavaScript đều là một comment, và bất kỳ cái gì kèm theo như thế này `//` đều là comment.
**Ví dụ: Comment 1 dòng**
```js
// Đây là comment thứ nhất
// Đây là comment thứ hai
// Đây là comment 1 dòng
```
**Ví dụ: Comment nhiều dòng**
```js
/*
Đây là comment nhiều dòng
Comment nhiều dòng có thể có nhiều dòng
JavaScript là ngôn ngữ của web
*/
```
##### Cú pháp
Ngôn ngữ lập trình tương tự như ngôn ngữ của con người. Tiếng Việt hoặc nhiều ngôn ngữ khác sử dụng các từ, cụm từ, câu, câu ghép và nhiều ngôn ngữ khác để truyền tải một thông điệp có ý nghĩa. Ý nghĩa cú pháp trong tiếng Việt là _sự sắp xếp các từ và cụm từ để tạo ra các câu có cấu trúc trong một ngôn ngữ_. Định nghĩa kỹ thuật của cú pháp là cấu trúc của các câu lệnh trong một ngôn ngữ máy tính. Ngôn ngữ lập trình cũng có cú pháp. JavaScript là một ngôn ngữ lập trình và giống như các ngôn ngữ lập trình khác, nó có cú pháp riêng. Nếu chúng ta không viết một cú pháp mà JavaScript hiểu, nó sẽ phát sinh các loại lỗi khác nhau. Chúng ta sẽ khám phá các loại lỗi trong JavaScript khác nhau ở phần sau. Bây giờ, hãy xem 1 cú pháp bị lỗi bên dưới.
![Lỗi](../images/raising_syntax_error.png)
Tôi đã phạm một sai lầm có chủ ý. Kết quả là console làm tăng lỗi cú pháp. Trên thực tế, cú pháp rất nhiều thông tin. Nó thông báo loại sai lầm đã được thực hiện. Bằng cách đọc hướng dẫn phản hồi lỗi, chúng ta có thể sửa cú pháp và khắc phục sự cố. Quá trình xác định và loại bỏ lỗi khỏi chương trình được gọi là gỡ lỗi (debug). Bây giờ chúng ta sẽ gỡ lỗi:
```js
console.log('Hello, World!')
console.log('Hello, World!')
```
Hiện tại, chúng ta đã thấy cách hiển thị văn bản bằng cách sử dụng _`console.log()`_. Nếu chúng ta in văn bản hoặc chuỗi bằng cách sử dụng _`console.log()`_, văn bản phải nằm trong dấu nháy đơn, dấu ngoặc kép hoặc que ngược.
**Ví dụ:**
```js
console.log('Hello, World!')
console.log("Hello, World!")
console.log(`Hello, World!`)
```
#### Toán tử
Bây giờ, chúng ta sẽ viết code JavaScript nhiều hơn bằng cách sử dụng _`console.log()`_ trên console của Google Chrome cho các kiểu dữ liệu số. Ngoài văn bản, chúng ta cũng có thể thực hiện các phép tính toán bằng JavaScript. Chúng ta sẽ thực hiện các phép tính đơn giản sau. Có thể viết code JavaScript trên console Google Chrome trực tiếp mà không cần hàm **_`console.log()`_**. Tuy nhiên, nó được đưa vào phần này vì hầu hết thử thách này sẽ diễn ra trong code editor, nơi việc sử dụng hàm là bắt buộc.
![Toán tử](../images/arithmetic.png)
```js
console.log(2 + 3) // Cộng
console.log(3 - 2) // Trừ
console.log(2 * 3) // Nhân
console.log(3 / 2) // Chia
console.log(3 % 2) // Chia lấy dư
console.log(3 ** 2) // Luỹ thừa 3 ** 2 == 3 * 3
```
### Code Editor
Chúng ta có thể viết code trên console của trình duyệt, nhưng nó sẽ không dành cho các dự án lớn hơn. Trong môi trường làm việc thực tế, các lập trình viên sử dụng các code editor khác nhau để viết code. Trong thử thách Học JavaScript trong 30 ngày này, chúng ta sẽ sử dụng Visual Studio Code.
#### Cài Visual Studio Code
Visual Studio Code là một trình soạn thảo văn bản nguồn mở rất phổ biến. Tôi muốn giới thiệu bạn [tải Visual Studio Code](https://code.visualstudio.com/), nhưng nếu bạn muốn sử dụng các editor, hãy thoải mái làm theo những gì bạn có.
![Vscode](../images/vscode.png)
Nếu bạn đã cài đặt Visual Studio Code, bây giờ chúng ta sẽ sử dụng nó.
#### Cách sử dụng Visual Studio Code
Mở Visual Studio Code bằng cách nhấp đúp vào biểu tượng. Khi đã mở, bạn sẽ thấy giao diện như này. Hãy làm quen với các phần mà được đánh dấu.
![Vscode ui](../images/vscode_ui.png)
![Vscode thêm mới dự án](../images/adding_project_to_vscode.png)
![Vscode mở dự án](../images/opening_project_on_vscode.png)
![file script](../images/scripts_on_vscode.png)
![Cài Live Server](../images/vsc_live_server.png)
![chạy script](../images/running_script.png)
![chạy code](../images/launched_on_new_tab.png)
## Thêm JavaScript vào trang web
JavaScript có thể thêm vào trang web bằng 3 cách:
- **_Inline script_**
- **_Internal script_**
- **_External script_**
- **_Multiple External scripts_**
Các phần sau đây sẽ hướng dẫn các cách khác nhau để thêm code JavaScript vào trang web.
### Inline Script
Tạo thư mục trên màn hình hoặc ở bất kỳ vị trí nào, đặt tên là 30DaysOfJS và tạo tệp có tên **_`index.html`_**. Sau đó, dán mã sau và mở nó trong trình duyệt, ví dụ [Chrome](https://www.google.com/chrome/).
```html
<!DOCTYPE html>
<html lang="vi">
<head>
<title>30DaysOfScript:Inline Script</title>
</head>
<body>
<button onclick="alert('Chào bạn đến với 30DaysOfJavaScript!')">Nhấp vàod đây</button>
</body>
</html>
```
Bây giờ, bạn vừa viết inline script (nhúng trực tiếp) đầu tiên của mình. Chúng tôi có thể tạo một popup cảnh báo bằng cách sử dụng hàm có sẵn _`alert()`_ .
### Internal Script
Internal Script có thể được viết trong thẻ _`head`_ hoặc _`body`_, nhưng nó sẽ được ưu tiên chạy trước khi viết trong phần body của tệp HTML.
Trước tiên, chúng ta hãy viết trên phần head của trang.
```html
<!DOCTYPE html>
<html lang="vi">
<head>
<title>30DaysOfScript:Internal Script</title>
<script>
console.log('Chào bạn đến với 30DaysOfJavaScript')
</script>
</head>
<body></body>
</html>
```
Đây là cách chúng ta sẽ viết Inernal Script trong thử thách này. Viết code JavaScript trong phần body là tùy chọn ưu tiên nhất. Mở console của trình duyệt để xem kết quả từ `console.log()`.
```html
<!DOCTYPE html>
<html lang="vi">
<head>
<title>30DaysOfScript:Internal Script</title>
</head>
<body>
<button onclick="alert('Chào bạn đến với 30DaysOfJavaScript!');">Click Me</button>
<script>
console.log('Chào bạn đến với 30DaysOfJavaScript')
</script>
</body>
</html>
```
Mở console của trình duyệt để xem kết quả từ `console.log()`.
![js code từ vscode](../images/js_code_vscode.png)
### External Script
Tương tự như Internal Script, External Script có thể nằm trên header hoặc body, nhưng tốt hơn là đặt nó trong phần body.
Đầu tiên, chúng ta sẽ tạo một tệp JavaScript có đuôi là `.js`. Tất cả tệp JavaScript đều có đuôi là `.js`. Tạo một tệp có tên là `Introduction.js` bên trong thư mục vừa nảy bạn đã tạo và viết code sau và nhúng tệp .js này vào cuối phần body.
```js
console.log('Chào bạn đến với 30DaysOfJavaScript')
```
Nhúng External scripts trong thẻ _head_:
```html
<!DOCTYPE html>
<html lang="vi">
<head>
<title>30DaysOfJavaScript:External script</title>
<script src="introduction.js"></script>
</head>
<body></body>
</html>
```
Nhúng External scripts trong thẻ _body_:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:External script</title>
</head>
<body>
<!-- Liên kết bên ngoài JavaScript có thể nằm trong header hoặc trong body -->
<!-- Trước thẻ đóng của phần body là nơi được khuyến nghị để nhúng các tệp JavaScript bên ngoài -->
<script src="introduction.js"></script>
</body>
</html>
```
Mở console trình duyệt để xem kết quả của `console.log()`.
### Nhúng nhiều External Scripts
Chúng ta cũng có thể nhúng nhiều tệp JavaScript bên ngoài trong một trang web.
Tạo tệp `helloworld.js` trong thư mục 30DaysOfJS và viết theo code bên dưới.
```js
console.log('Hello, World!')
```
```html
<!DOCTYPE html>
<html lang="vi">
<head>
<title>Multiple External Scripts</title>
</head>
<body>
<script src="./helloworld.js"></script>
<script src="./introduction.js"></script>
</body>
</html>
```
_Tệp main.js của bạn phải nằm bên dưới tất cả các script khác_. Điều rất quan trọng là phải nhớ điều này.
![Nhiều Script](../images/multiple_script.png)
## Giới thiệu các kiểu các dữ liệu
Trong JavaScript và các ngôn ngữ lập trình khác, có nhiều kiểu dữ liệu khác nhau. Sau đây là các kiểu dữ liệu nguyên thủy của JavaScript: _String, Number, Boolean, undefined, Null_, và _Symbol_.
### Numbers (số)
- Số nguyên: Số nguyên (âm, 0 và dương)
Ví dụ:
... -3, -2, -1, 0, 1, 2, 3 ...
- Số thập phân
Ví dụ
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
### Strings (Chuỗi)
Tập hợp một hoặc nhiều ký tự nằm giữa hai nháy đơn, dấu nháy kép hoặc gạch chéo.
**Ví dụ:**
```js
'a'
'Asabeneh'
"Asabeneh"
'Việt Nam'
'JavaScript là ngôn ngữ lập trình tuyệt nhất'
'Tôi thích chia sẻ'
'Tôi hy vọng bạn đang tận hưởng ngày đầu tiên'
`Chúng ta cũng có thể tạo một chuỗi bằng cách sử dụng một gạch chéo`
'Một chuỗi có thể chỉ nhỏ bằng một ký tự hoặc lớn bằng nhiều trang'
'Bất kỳ loại dữ liệu nào dưới dấu nháy đơn, dấu nháy kép hoặc gạch chéo đều là một chuỗi'
```
### Booleans
Giá trị boolean là `True` hoặc `False`. Mọi phép so sánh đều trả về giá trị boolean, đúng hoặc sai.
Kiểu dữ liệu boolean là giá trị `true` hoặc `false`.
**Ví dụ:**
```js
true // nếu đèn sáng, giá trị là true
false // nếu đèn tắt, giá trị là false
```
### Undefined
Trong JavaScript, nếu chúng ta không gán giá trị cho một biến thì giá trị đó không được xác định. Ngoài ra, nếu một hàm không trả về bất cứ thứ gì, nó sẽ trả về không xác định.
```js
let firstName
console.log(firstName) // undefined, bởi vì nó chưa được gán cho một giá trị nào
```
### Null
Null trong JavaScript có nghĩa là một biến rỗng.
```js
let emptyValue = null
```
## Xác định kiểu dữ liệu
Để kiểm tra kiểu dữ liệu của một biến, chúng ta sử dụng **typeof**. Xem ví dụ bên dưới.
```js
console.log(typeof 'Asabeneh') // string
console.log(typeof 5) // number
console.log(typeof true) // boolean
console.log(typeof null) // object type
console.log(typeof undefined) // undefined
```
## Comments lần nữa
Hãy nhớ rằng comment trong JavaScript cũng tương tự như các ngôn ngữ lập trình khác. Comment rất quan trọng trong việc làm cho code của bạn dễ đọc hơn.
Có hai cách comment:
- _Comment 1 dòng_
- _Comment nhiều dòng_
```js
// comment chính nó là một comment 1 dòng
// let firstName = 'Asabeneh'; comment 1 dòng
// let lastName = 'Yetayeh'; comment 1 dòng
```
Comment nhiều dòng:
```js
/*
let location = 'Helsinki';
let age = 100;
let isMarried = true;
Đây là comment nhiều dòng
*/
```
## Biến
Biến là _vùng chứa_ của dữ liệu. Các biến được sử dụng để _lưu trữ_ dữ liệu trong vị trí bộ nhớ. Khi một biến được khai báo, một vị trí bộ nhớ được dành riêng. Khi gán giá trị (dữ liệu) cho một biến, không gian bộ nhớ sẽ được lấp đầy bởi dữ liệu đó. Để khai báo một biến, chúng ta sử dụng các từ khóa _var_, _let_, hoặc _const_.
Đối với một biến chúng ta cần thay đổi dữ liệu sau này, chúng ta sử dụng _let_. Nếu dữ liệu của biến đó không cần thay đổi thì chúng ta sử dụng _const_. Ví dụ, PI, tên quốc gia, trọng lực, các đối tượng này không thay đổi dữ liệu thì dùng _const_. Chúng ta sẽ không sử dụng `var` trong thử thách này và tôi không khuyên bạn nên sử dụng nó. Đây là cách dễ bị lỗi khi khai báo biến, nó có rất nhiều lỗ hổng. Chúng ta sẽ nói chi tiết hơn về `var`, `let``const` trong các phần khác. Còn bây giờ, lời giải thích trên là đủ.
Tên biến JavaScript hợp lệ phải tuân theo các quy tắc sau:
- Tên biến JavaScript không được bắt đầu bằng một số.
- Tên biến JavaScript không được có ký tự đặc biệt ngoại trừ ký tự $ và dấu gạch dưới _.
- Tên biến JavaScript tuân theo quy ước camelCase.
- Tên biến JavaScript không được có khoảng trắng giữa các từ.
Sau đây là các ví dụ về các biến JavaScript hợp lệ.
```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
```
Hai biến đầu tiên bên trên tuân theo quy ước camelCase về khai báo trong JavaScript. Trong tài liệu này, chúng tôi sẽ sử dụng các biến camelCase (camelWithOneHump). Chúng ta sử dụng CamelCase (CamelWithTwoHump) để khai báo các lớp, chúng ta sẽ thảo luận về các lớp và đối tượng trong phần khác.
Ví dụ về các biến không hợp lệ:
```js
first-name
1_num
num_#_1
```
Chúng ta hãy khai báo các biến với các kiểu dữ liệu khác nhau. Để khai báo 1 biến, sử dụng từ khoá _let_ hoặc _const_ trước tên biến. Theo sau tên biến, chúng ta viết một dấu bằng (toán tử gán) và một giá trị (dữ liệu được gán).
```js
// Cú pháp
let tenBien = giatri
```
Tên biến là tên lưu trữ các dữ liệu có giá trị khác nhau. Xem bên dưới để biết các ví dụ chi tiết.
**Ví dụ về khai báo biến**
```js
// Khai báo biến với các kiểu dữ liệu các nhau
let firstName = 'Đạt' // tên của 1 người
let lastName = 'Ngô Quốc' // họ của 1 người
let country = 'Việt Nam' // quốc gia
let city = 'Hà Nội' // thủ đô
let age = 19 // tuổi
let isMarried = false // đã cưới hay chưa
console.log(firstName, lastName, country, city, age, isMarried)
```
```sh
Đạt Ngô Quốc Việt Nam Hà Nội 19 false
```
```js
// Khai báo biến với kiểu dữ liệu số
let age = 100 // tuổi
const gravity = 9.81 // trọng lực trái đất m/s2
const boilingPoint = 100 // độ sôi của nước, nhiệt độ tính bằng °C
const PI = 3.14 // số PI
console.log(gravity, boilingPoint, PI)
```
```sh
9.81 100 3.14
```
```js
// Bạn cũngc có thể khai báo biến trên 1 dòng phân cách bằng dấu phẩy, tuy nhiên, tôi khuyên bạn nên sử dụng một dòng riêng biệt để làm cho code dễ đọc hơn
let name = 'Ngô Quốc Đạt', job = 'developer', live = 'Việt Nam'
console.log(name, job, live)
```
```sh
Ngô Quốc Đạt developer Việt Nam
```
Khi bạn chạy tệp _index.html_ trong thư mục 01-Day bạn sẽ thấy như này:
![Ngày 1](../images/day_1.png)
🌕 Bạn thật tuyệt! Bạn vừa hoàn thành thử thách ngày 1 và bạn đang trên đường vươn tới sự vĩ đại. Bây giờ hãy thực hiện một số bài tập cho não và cơ bắp của bạn.
# 💻 Ngày 1: Bài tập
1. Viết 1 dòng comment nói là, _comment làm code dễ đọc hơn_
2. Viết 1 dòng comment khác nói là, _Chào mừng bạn đến với 30DaysOfJavaScript_
3. Viết comment nhiều dòng nói là, _comment làm code dễ đọc hơn, dễ sử dụng lại_ _và chi tiết_
4. Tạo tệp `variable.js` và khai báo các biến và gán các kiểu dữ liệu `string`, `boolean`, `undefined``null`.
5. Tạo tệp `datatypes.js` và sử dụng **_typeof_** để kiểm tra các kiểu dữ liệu khác nhau. Kiểm tra kiểu dữ liệu của từng biến.
6. Khai báo 4 biến không gán giá trị
7. Khai báo 4 biến có gán giá trị
8. Khai báo các biến để lưu trữ họ, tên, tình trạng hôn nhân, quốc gia và tuổi của bạn trong nhiều dòng
9. Khai báo các biến để lưu trữ họ, tên, tình trạng hôn nhân, quốc gia và tuổi của bạn trong một dòng duy nhất
10. Khai báo 2 biến _myAge__yourAge_ và gán giá trị cho nó, và xuất nó ra trên console của trình duyệt.
```sh
I am 25 years old.
You are 30 years old.
```
🎉 CHÚC MỪNG ! 🎉
[Ngày 2 >>](./02_Day_Data_types/02_day_data_types.md)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -54,13 +54,16 @@
<small> January, 2020</small>
</sub>
<div>
<div>
🇬🇧 [English](./readMe.md)
🇪🇸 [Spanish](./Spanish/readme.md)
🇷🇺 [Russian](./RU/README.md)
🇦🇿 [Azerbaijan](./Azerbaijani/readMe.md)
KR [Korean](./Korea/README.md)
🇻🇳 [Vietnamese](./Vietnamese/README.md)
</div>
</div>
</div>
</div>
@ -71,36 +74,36 @@
- [30 Days Of JavaScript](#30-days-of-javascript)
- [📔 Day 1](#-day-1)
- [Introduction](#introduction)
- [Requirements](#requirements)
- [Setup](#setup)
- [Install Node.js](#install-nodejs)
- [Browser](#browser)
- [Installing Google Chrome](#installing-google-chrome)
- [Opening Google Chrome Console](#opening-google-chrome-console)
- [Writing Code on Browser Console](#writing-code-on-browser-console)
- [Console.log](#consolelog)
- [Console.log with Multiple Arguments](#consolelog-with-multiple-arguments)
- [Comments](#comments)
- [Syntax](#syntax)
- [Arithmetics](#arithmetics)
- [Code Editor](#code-editor)
- [Installing Visual Studio Code](#installing-visual-studio-code)
- [How to Use Visual Studio Code](#how-to-use-visual-studio-code)
- [Adding JavaScript to a Web Page](#adding-javascript-to-a-web-page)
- [Inline Script](#inline-script)
- [Internal Script](#internal-script)
- [External Script](#external-script)
- [Multiple External Scripts](#multiple-external-scripts)
- [Introduction to Data types](#introduction-to-data-types)
- [Numbers](#numbers)
- [Strings](#strings)
- [Booleans](#booleans)
- [Undefined](#undefined)
- [Null](#null)
- [Checking Data Types](#checking-data-types)
- [Comments Again](#comments-again)
- [Variables](#variables)
- [Introduction](#introduction)
- [Requirements](#requirements)
- [Setup](#setup)
- [Install Node.js](#install-nodejs)
- [Browser](#browser)
- [Installing Google Chrome](#installing-google-chrome)
- [Opening Google Chrome Console](#opening-google-chrome-console)
- [Writing Code on Browser Console](#writing-code-on-browser-console)
- [Console.log](#consolelog)
- [Console.log with Multiple Arguments](#consolelog-with-multiple-arguments)
- [Comments](#comments)
- [Syntax](#syntax)
- [Arithmetics](#arithmetics)
- [Code Editor](#code-editor)
- [Installing Visual Studio Code](#installing-visual-studio-code)
- [How to Use Visual Studio Code](#how-to-use-visual-studio-code)
- [Adding JavaScript to a Web Page](#adding-javascript-to-a-web-page)
- [Inline Script](#inline-script)
- [Internal Script](#internal-script)
- [External Script](#external-script)
- [Multiple External Scripts](#multiple-external-scripts)
- [Introduction to Data types](#introduction-to-data-types)
- [Numbers](#numbers)
- [Strings](#strings)
- [Booleans](#booleans)
- [Undefined](#undefined)
- [Null](#null)
- [Checking Data Types](#checking-data-types)
- [Comments Again](#comments-again)
- [Variables](#variables)
- [💻 Day 1: Exercises](#-day-1-exercises)
# 📔 Day 1
@ -148,7 +151,7 @@ asabeneh $ node -v
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 v14.17.6.
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
@ -197,7 +200,7 @@ Ctl+Shift+I
##### 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
console.log('Hello, World!')
@ -205,7 +208,7 @@ console.log('Hello, World!')
##### Console.log with Multiple Arguments
The **console.log()** function can take multiple parameters separated by commas. 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)
@ -215,31 +218,35 @@ console.log('HAPPY', 'NEW', 'YEAR', 2020)
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
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**
```js
// This is the first comment
// This is the second comment
// I am a single line comment
// This is the second comment
// I am a single line comment
```
**Example: Multiline Comment**
```js
/*
This is a multiline comment
Multiline comments can take multiple lines
JavaScript is the language of the web
*/
```
##### 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.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.
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)
@ -250,7 +257,7 @@ 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:**
```js
@ -261,9 +268,9 @@ console.log(`Hello, World!`)
#### 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.
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)
@ -278,11 +285,11 @@ console.log(3 ** 2) // Exponentiation 3 ** 2 == 3 * 3
### 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
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)
@ -319,11 +326,11 @@ The following sections show different ways of adding JavaScript code to your web
### 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
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfScript:Inline Script</title>
</head>
@ -333,16 +340,16 @@ Create a project folder on your desktop or in any location, name it 30DaysOfJS a
</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
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.
```html
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfScript:Internal Script</title>
<script>
@ -353,11 +360,11 @@ First, let us write on the head part of the page.
</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
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfScript:Internal Script</title>
</head>
@ -370,7 +377,7 @@ This is how we write an internal script most of the time. Writing the JavaScript
</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)
@ -387,7 +394,7 @@ External scripts in the _head_:
```html
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:External script</title>
<script src="introduction.js"></script>
@ -400,24 +407,24 @@ External scripts in the _body_:
```html
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>30DaysOfJavaScript:External script</title>
</head>
<body>
<!-- it could be in the header or in the body -->
<!-- Here is the recommended place to put the external script -->
<!-- JavaScript external link could be in the header or in the body -->
<!-- Before the closing tag of the body is the recommended place to put the external JavaScript script -->
<script src="introduction.js"></script>
</body>
</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
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
console.log('Hello, World!')
@ -425,7 +432,7 @@ console.log('Hello, World!')
```html
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<title>Multiple External Scripts</title>
</head>
@ -442,7 +449,7 @@ _Your main.js file should be below all other scripts_. It is very important to r
## 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
@ -456,16 +463,20 @@ In JavaScript and also other programming languages, there are different kinds of
### Strings
A collection of one or more characters between two single quotes, double quotes, or backticks.
**Example:**
```js
'a'
'Asabeneh'
"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'
'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
@ -532,7 +543,6 @@ Multiline commenting:
let age = 100;
let isMarried = true;
This is a Multiple line comment
*/
```
@ -573,11 +583,11 @@ year2020
year_2020
```
The first and second variables on the list follows the camelCase convention of declaring in JavaScript. 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:
```sh
```js
first-name
1_num
num_#_1
@ -590,6 +600,8 @@ Let us declare variables with different data types. To declare a variable, we ne
let nameOfVariable = value
```
The nameOfVriable is the name that stores different data of value. See below for detail examples.
**Examples of declared variables**
```js
@ -622,10 +634,8 @@ console.log(gravity, boilingPoint, PI)
```
```js
// Variables can also be declaring in one line separated by comma
let name = 'Asabeneh', // name of a person
job = 'teacher',
live = 'Finland'
// 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', job = 'teacher', live = 'Finland'
console.log(name, job, live)
```

Loading…
Cancel
Save