Merge pull request #285 from datlechin/master

Vietnamese translation - Day 2 (wip)
pull/286/head
Asabeneh 4 years ago committed by GitHub
commit 3ca1a9ff0f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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)

@ -323,75 +323,75 @@ Các phần sau đây sẽ hướng dẫn các cách khác nhau để thêm code
### Inline Script ### Inline Script
Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_`index.html`_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/). 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 ```html
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="vi">
<head> <head>
<title>30DaysOfScript:Inline Script</title> <title>30DaysOfScript:Inline Script</title>
</head> </head>
<body> <body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!')">Click Me</button> <button onclick="alert('Chào bạn đến với 30DaysOfJavaScript!')">Nhấp vàod đây</button>
</body> </body>
</html> </html>
``` ```
Now, you just wrote your first inline script. We can create a pop up alert message using the _`alert()`_ built-in function. 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
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. 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.
First, let us write on the head part of the page. Trước tiên, chúng ta hãy viết trên phần head của trang.
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="vi">
<head> <head>
<title>30DaysOfScript:Internal Script</title> <title>30DaysOfScript:Internal Script</title>
<script> <script>
console.log('Welcome to 30DaysOfJavaScript') console.log('Chào bạn đến với 30DaysOfJavaScript')
</script> </script>
</head> </head>
<body></body> <body></body>
</html> </html>
``` ```
This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the `console.log()`. Đâ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 ```html
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="vi">
<head> <head>
<title>30DaysOfScript:Internal Script</title> <title>30DaysOfScript:Internal Script</title>
</head> </head>
<body> <body>
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button> <button onclick="alert('Chào bạn đến với 30DaysOfJavaScript!');">Click Me</button>
<script> <script>
console.log('Welcome to 30DaysOfJavaScript') console.log('Chào bạn đến với 30DaysOfJavaScript')
</script> </script>
</body> </body>
</html> </html>
``` ```
Open the browser console to see the output from the `console.log()`. Mở console của trình duyệt để xem kết quả từ `console.log()`.
![js code from vscode](../images/js_code_vscode.png) ![js code từ vscode](../images/js_code_vscode.png)
### External Script ### External Script
Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body. 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.
First, we should create an external JavaScript file with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body. Đầ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 ```js
console.log('Welcome to 30DaysOfJavaScript') console.log('Chào bạn đến với 30DaysOfJavaScript')
``` ```
External scripts in the _head_: Nhúng External scripts trong thẻ _head_:
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="vi">
<head> <head>
<title>30DaysOfJavaScript:External script</title> <title>30DaysOfJavaScript:External script</title>
<script src="introduction.js"></script> <script src="introduction.js"></script>
@ -400,7 +400,7 @@ External scripts in the _head_:
</html> </html>
``` ```
External scripts in the _body_: Nhúng External scripts trong thẻ _body_:
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
@ -409,19 +409,19 @@ External scripts in the _body_:
<title>30DaysOfJavaScript:External script</title> <title>30DaysOfJavaScript:External script</title>
</head> </head>
<body> <body>
<!-- JavaScript external link could be in the header or in the body --> <!-- Liên kết bên ngoài JavaScript có thể nằm trong header hoặc trong body -->
<!-- Before the closing tag of the body is the recommended place to put the external JavaScript script --> <!-- 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> <script src="introduction.js"></script>
</body> </body>
</html> </html>
``` ```
Open the browser console to see the output of the `console.log()`. Mở console trình duyệt để xem kết quả của `console.log()`.
### Multiple External Scripts ### Nhúng nhiều External Scripts
We can also link multiple external JavaScript files to a web page. Chúng ta cũng có thể nhúng nhiều tệp JavaScript bên ngoài trong một trang web.
Create a `helloworld.js` file inside the 30DaysOfJS folder and write the following code. Tạo tệp `helloworld.js` trong thư mục 30DaysOfJS và viết theo code bên dưới.
```js ```js
console.log('Hello, World!') console.log('Hello, World!')
@ -429,7 +429,7 @@ console.log('Hello, World!')
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="vi">
<head> <head>
<title>Multiple External Scripts</title> <title>Multiple External Scripts</title>
</head> </head>
@ -440,26 +440,26 @@ console.log('Hello, World!')
</html> </html>
``` ```
_Your main.js file should be below all other scripts_. It is very important to remember this. _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.
![Multiple Script](../images/multiple_script.png) ![Nhiều Script](../images/multiple_script.png)
## Introduction to Data types ## Giới thiệu các kiểu các dữ liệu
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_. 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 ### Numbers (số)
- Integers: Integer (negative, zero and positive) numbers - Số nguyên: Số nguyên (âm, 0 và dương)
Ví dụ: Ví dụ:
... -3, -2, -1, 0, 1, 2, 3 ... ... -3, -2, -1, 0, 1, 2, 3 ...
- Float-point numbers: Decimal number - Số thập phân
Example Ví dụ
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
### Strings ### Strings (Chuỗi)
A collection of one or more characters between two single quotes, double quotes, or backticks. 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ụ:** **Ví dụ:**
@ -467,48 +467,48 @@ A collection of one or more characters between two single quotes, double quotes,
'a' 'a'
'Asabeneh' 'Asabeneh'
"Asabeneh" "Asabeneh"
'Finland' 'Việt Nam'
'JavaScript is a beautiful programming language' 'JavaScript là ngôn ngữ lập trình tuyệt nhất'
'I love teaching' 'Tôi thích chia sẻ'
'I hope you are enjoying the first day' 'Tôi hy vọng bạn đang tận hưởng ngày đầu tiên'
`We can also create a string using a backtick` `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`
'A string could be just as small as one character or as big as many pages' 'Một chuỗi có thể chỉ nhỏ bằng một ký tự hoặc lớn bằng nhiều trang'
'Any data type under a single quote, double quote or backtick is a string' '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 ### Booleans
A boolean value is either True or False. Any comparisons returns a boolean value, which is either true or false. 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.
A boolean data type is either a true or false value. Kiểu dữ liệu boolean là giá trị `true` hoặc `false`.
**Ví dụ:** **Ví dụ:**
```js ```js
true // if the light is on, the value is true true // nếu đèn sáng, giá trị là true
false // if the light is off, the value is false false // nếu đèn tắt, giá trị là false
``` ```
### Undefined ### Undefined
In JavaScript, if we don't assign a value to a variable, the value is undefined. In addition to that, if a function is not returning anything, it returns 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 ```js
let firstName let firstName
console.log(firstName) // undefined, because it is not assigned to a value yet console.log(firstName) // undefined, bởi vì nó chưa được gán cho một giá trị nào
``` ```
### Null ### Null
Null in JavaScript means an empty value. Null trong JavaScript có nghĩa là một biến rỗng.
```js ```js
let emptyValue = null let emptyValue = null
``` ```
## Checking Data Types ## Xác định kiểu dữ liệu
To check the data type of a certain variable, we use the **typeof** operator. See the following example. Để 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 ```js
console.log(typeof 'Asabeneh') // string console.log(typeof 'Asabeneh') // string
@ -518,45 +518,45 @@ console.log(typeof null) // object type
console.log(typeof undefined) // undefined console.log(typeof undefined) // undefined
``` ```
## Comments Again ## Comments lần nữa
Remember that commenting in JavaScript is similar to other programming languages. Comments are important in making your code more readable. 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.
There are two ways of commenting: Có hai cách comment:
- _Single line commenting_ - _Comment 1 dòng_
- _Multiline commenting_ - _Comment nhiều dòng_
```js ```js
// commenting the code itself with a single comment // comment chính nó là một comment 1 dòng
// let firstName = 'Asabeneh'; single line comment // let firstName = 'Asabeneh'; comment 1 dòng
// let lastName = 'Yetayeh'; single line comment // let lastName = 'Yetayeh'; comment 1 dòng
``` ```
Multiline commenting: Comment nhiều dòng:
```js ```js
/* /*
let location = 'Helsinki'; let location = 'Helsinki';
let age = 100; let age = 100;
let isMarried = true; let isMarried = true;
This is a Multiple line comment Đây là comment nhiều dòng
*/ */
``` ```
## Variables ## Biến
Variables are _containers_ of data. Variables are used to _store_ data in a memory location. When a variable is declared, a memory location is reserved. When a variable is assigned to a value (data), the memory space will be filled with that data. To declare a variable, we use _var_, _let_, or _const_ keywords. 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_.
For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do not change, and we can use _const_. We will not use var in this challenge and I don't recommend you to use it. It is error prone way of declaring variable it has lots of leak. We will talk more about var, let, and const in detail in other sections (scope). For now, the above explanation is enough. Đố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à đủ.
A valid JavaScript variable name must follow the following rules: Tên biến JavaScript hợp lệ phải tuân theo các quy tắc sau:
- A JavaScript variable name should not begin with a number. - Tên biến JavaScript không được bắt đầu bằng một số.
- A JavaScript variable name does not allow special characters except dollar sign and underscore. - 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 _.
- A JavaScript variable name follows a camelCase convention. - Tên biến JavaScript tuân theo quy ước camelCase.
- A JavaScript variable name should not have space between words. - Tên biến JavaScript không được có khoảng trắng giữa các từ.
The following are examples of valid JavaScript variables. Sau đây là các ví dụ về các biến JavaScript hợp lệ.
```js ```js
firstName firstName
@ -580,9 +580,9 @@ year2020
year_2020 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(camelWithOneHump). We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about classes and objects in other section. 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.
Example of invalid variables: Ví dụ về các biến không hợp lệ:
```js ```js
first-name first-name
@ -590,39 +590,39 @@ Example of invalid variables:
num_#_1 num_#_1
``` ```
Let us declare variables with different data types. To declare a variable, we need to use _let_ or _const_ keyword before the variable name. Following the variable name, we write an equal sign (assignment operator), and a value(assigned data). 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 ```js
// Syntax // Cú pháp
let nameOfVariable = value let tenBien = giatri
``` ```
The nameOfVriable is the name that stores different data of value. See below for detail examples. 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.
**Examples of declared variables** **Ví dụ về khai báo biến**
```js ```js
// Declaring different variables of different data types // Khai báo biến với các kiểu dữ liệu các nhau
let firstName = 'Asabeneh' // first name of a person let firstName = 'Đạt' // tên của 1 người
let lastName = 'Yetayeh' // last name of a person let lastName = 'Ngô Quốc' // họ của 1 người
let country = 'Finland' // country let country = 'Việt Nam' // quốc gia
let city = 'Helsinki' // capital city let city = 'Hà Nội' // thủ đô
let age = 100 // age in years let age = 19 // tuổi
let isMarried = true let isMarried = false // đã cưới hay chưa
console.log(firstName, lastName, country, city, age, isMarried) console.log(firstName, lastName, country, city, age, isMarried)
``` ```
```sh ```sh
Asabeneh Yetayeh Finland Helsinki 100 true Đạt Ngô Quốc Việt Nam Hà Nội 19 false
``` ```
```js ```js
// Declaring variables with number values // Khai báo biến với kiểu dữ liệu số
let age = 100 // age in years let age = 100 // tuổi
const gravity = 9.81 // earth gravity in m/s2 const gravity = 9.81 // trọng lực trái đất m/s2
const boilingPoint = 100 // water boiling point, temperature in °C const boilingPoint = 100 // độ sôi của nước, nhiệt độ tính bằng °C
const PI = 3.14 // geometrical constant const PI = 3.14 // số PI
console.log(gravity, boilingPoint, PI) console.log(gravity, boilingPoint, PI)
``` ```
@ -631,41 +631,39 @@ console.log(gravity, boilingPoint, PI)
``` ```
```js ```js
// Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble // 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 = 'Asabeneh', job = 'teacher', live = 'Finland' let name = 'Ngô Quốc Đạt', job = 'developer', live = 'Việt Nam'
console.log(name, job, live) console.log(name, job, live)
``` ```
```sh ```sh
Asabeneh teacher Finland Ngô Quốc Đạt developer Việt Nam
``` ```
When you run _index.html_ file in the 01-Day folder you should get this: 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 one](../images/day_1.png)
🌕 You are amazing! You have just completed day 1 challenge and you are on your way to greatness. Now do some exercises for your brain and muscle. ![Ngày 1](../images/day_1.png)
# 💻 Ngày 1: Exercises 🌕 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.
1. Write a single line comment which says, _comments can make code readable_ # 💻 Ngày 1: Bài tập
2. Write another single comment which says, _Welcome to 30DaysOfJavaScript_
3. Write a multiline comment which says, _comments can make code readable, easy to reuse_
_and informative_
4. Create a variable.js file and declare variables and assign string, boolean, undefined and null data types 1. Viết 1 dòng comment nói là, _comment làm code dễ đọc hơn_
5. Create datatypes.js file and use the JavaScript **_typeof_** operator to check different data types. Check the data type of each variable 2. Viết 1 dòng comment khác nói là, _Chào mừng bạn đến với 30DaysOfJavaScript_
6. Declare four variables without assigning values 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_
7. Declare four variables with assigned values 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`.
8. Declare variables to store your first name, last name, marital status, country and age in multiple lines 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.
9. Declare variables to store your first name, last name, marital status, country and age in a single line 6. Khai báo 4 biến không gán giá trị
10. Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to the browser console. 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 ```sh
I am 25 years old. I am 25 years old.
You are 30 years old. You are 30 years old.
``` ```
🎉 CONGRATULATIONS ! 🎉 🎉 CHÚC MỪNG ! 🎉
[Ngày 2 >>](./02_Day_Data_types/02_day_data_types.md) [Ngày 2 >>](./02_Day_Data_types/02_day_data_types.md)

Loading…
Cancel
Save