- [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)
# 📔 Dia 2
## Tipos de Dados
Na sessão anterior, nós mencionamos um pouco sobre tipos de dados. Tipos de dados decrevem as caracteristicas do dado, e podem ser divididos em duas categorias:
1. Tipos de dados primitivos
2. Tipos de dados não primitivos(de referência do objeto.)
### Tipos de Dados Primitivos
Tipos de dados primitivos em JavaScript inclui:
1. Numbers - Inteiros, floats
2. Strings - Qualquer dado entre aspas simples, aspas duplas e crase
3. Booleans - valores verdadeiros e falsos
4. Null - valor vazio ou sem valor
5. Undefined - variável declarada sem um valor
6. Symbol - Um valor único que pode ser gerado por um construtor de símbolo
Tipos de dados não primitivos em JavaScriot inclui:
1. Objetos
2. Arrays
Agora, vamos ver exatamente oque significa tipos de dados primitivos e não primitivos.
*Primitivo* são tipos de dados imutáveis(nao-modificável). Uma vez criado um tipo de dado primitivo nós não podemos mais modifica-lo.
**Exemplo:**
```js
let word = 'JavaScript'
```
Se nós tentarmos modificar uma string armazenada na variável *word, JavaScrip irá mostar um error. Qualquer dados entre aspas simples, aspas duplas, ou aspas é um string tipo de dado.
```js
word[0] = 'Y'
```
Esta expressão não muda a string armazenada na variável *word*. Então, podemos dizer que strings não são modificavéis ou in outras palavras imutáveis.
Tipos de dados primitivos são comparados pelo seu valor. Vamos comparar valores de dados diferentes. Veja o exemplo abaixo:
```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
```
### Tipos de Dados Não Primitivos
*não primitivos* são tipos de dados modificáveis ou mutáveis. Nós podemos modificar o valor de um dado tipo não primitivo depois de criado.
Vamos ver isso criando um array. Um array é uma lista de valores de dados entre colchetes. Arrays que contém o mesmo ou diferente tipos de dados. Valores de Arrays são referenciados pelo seu index. Em JavaScript o index do array começa em zero. em outras palavras, o primeiro elemento de um array é encontrado no index zero, o segundo elemento no index um, e no terceiro elemento no index dois, etc.
```js
let nums = [1, 2, 3]
nums[0] = 1
console.log(nums) // [1, 2, 3]
```
Como você pode ver, um array, que é um tipo de dado não primitivo é mutável. Tipos de dados nao primitivos nao podem ser comparador pelos seus valores. Mesmo se dois tipos de dados não primitivos tem as mesmas propriedades e valores, eles não podem ser estritamentes iguais.
```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
```
Regra de ouro, nos nao comparamos tipos de dados nao primitivos. Nao se compara arrays, funções, ou objetos. porque eles são comparados pela sua referencia ao invez do valor. Dois objetos só são estritamentes iguais se a sua referência for o mesmo objeto subjacente.
```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.
## Números
Numbers are integers and decimal values which can do all the arithmetic operations.
Let's see some examples of Numbers.
### Declarando Tipos de Dados Numéricos
```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
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)
```
#### Random Number Generator
The JavaScript Math Object has a random() method number generator which generates number from 0 to 0.999999999...
```js
let randomNum = Math.random() // generates 0 to 0.999...
```
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 = ' ' // an empty space string
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.`
```
### String Concatenation
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
```
#### Long Literal Strings
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)
```
#### Escape Sequences in 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 30 Days Of JavaScript challenge.\nDo you ?') // line break
console.log('Days\tTopics\tExercises')
console.log('Day 1\t3\t5')
console.log('Day 2\t3\t5')
console.log('Day 3\t3\t5')
console.log('Day 4\t3\t5')
console.log('This is a 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 30 Days Of JavaScript challenge.
Do you ?
Days Topics Exercises
Day 1 3 5
Day 2 3 5
Day 3 3 5
Day 4 3 5
This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
In every programming language it starts with 'Hello, World!'
The saying 'Seeing is Believing' isn't correct in 2020
```
#### Template Literals (Template Strings)
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}`
```
**Example: 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
```
**Example: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
```
### String Methods
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.

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 = '30 Days Of JavaScript'
console.log(string.split()) // Changes to an array -> ["30 Days Of JavaScript"]
console.log(string.split(' ')) // Split to an array at space -> ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh'
console.log(firstName.split()) // 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"]
8. *trim()*: Removes trailing space in the beginning or the end of a string.
```js
let string = ' 30 Days Of JavaScript '
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
30 Days Of JavasCript
30 Days Of JavasCript
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 = '30 Days Of JavaScript'
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 = '30 Days Of JavaScript'
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
11. *charAt()*: Takes index and it returns the value at that index
```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()*: Takes index and it returns char code (ASCII number) of the value at that index
```js
string.charCodeAt(index)
```
```js
let string = '30 Days Of JavaScript'
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 = '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()*: 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.'
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]
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.
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
```
### Changing Data Type (Casting)
- Casting: Converting one data type to another data type. We use _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_
When we do arithmetic operations string numbers should be first converted to integer or float if not it returns an error.
#### String to Int
We can convert string number to a number. Any number inside a quote is a string number. An example of a string number: '10', '5', etc.
We can convert string 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 to Float
We can convert string float number to a float number. Any float number inside a quote is a string float number. An example of a string float number: '9.81', '3.14', '1.44', etc.
We can convert string float 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 to 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.
## 💻 Day 2: Exercises
### Exercise: Level 1
1. Declare a variable named challenge and assign it to an initial value **'30 Days Of JavaScript'**.
2. Print the string on the browser console using __console.log()__
3. Print the __length__ of the string on the browser console using _console.log()_
4. Change all the string characters to capital letters using __toUpperCase()__ method
5. Change all the string characters to lowercase letters using __toLowerCase()__ method
6. Cut (slice) out the first word of the string using __substr()__ or __substring()__ method
7. Slice out the phrase *Days Of JavaScript* from *30 Days Of JavaScript*.
8. Check if the string contains a word __Script__ using __includes()__ method
9. Split the __string__ into an __array__ using __split()__ method
10. Split the string 30 Days Of JavaScript at the space using __split()__ method
11. 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon' __split__ the string at the comma and change it to an array.
12. Change 30 Days Of JavaScript to 30 Days Of Python using __replace()__ method.
13. What is character at index 15 in '30 Days Of JavaScript' string? Use __charAt()__ method.
14. What is the character code of J in '30 Days Of JavaScript' string using __charCodeAt()__
15. Use __indexOf__ to determine the position of the first occurrence of __a__ in 30 Days Of JavaScript
16. Use __lastIndexOf__ to determine the position of the last occurrence of __a__ in 30 Days Of JavaScript.
17. Use __indexOf__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
18. Use __lastIndexOf__ to find the position of the last occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
19. Use __search__ to find the position of the first occurrence of the word __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
20. Use __trim()__ to remove any trailing whitespace at the beginning and the end of a string.E.g ' 30 Days Of JavaScript '.
21. Use __startsWith()__ method with the string *30 Days Of JavaScript* and make the result true
22. Use __endsWith()__ method with the string *30 Days Of JavaScript* and make the result true
23. Use __match()__ method to find all the __a__’s in 30 Days Of JavaScript
24. Use __concat()__ and merge '30 Days of' and 'JavaScript' to a single string, '30 Days Of JavaScript'
25. Use __repeat()__ method to print 30 Days Of JavaScript 2 times
### Exercise: Level 2
1. Using console.log() print out the following statement:
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help one another.
```
2. Using console.log() print out the following quote by Mother Teresa:
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
3. Check if typeof '10' is exactly equal to 10. If not make it exactly equal.
4. Check if parseFloat('9.8') is equal to 10 if not make it exactly equal with 10.
5. Check if 'on' is found in both python and jargon
6. _I hope this course is not full of jargon_. Check if _jargon_ is in the sentence.
7. Generate a random number between 0 and 100 inclusively.
8. Generate a random number between 50 and 100 inclusively.
9. Generate a random number between 0 and 255 inclusively.
10. Access the 'JavaScript' string characters using a random number.
11. Use console.log() and escape characters to print the following pattern.
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
12. Use __substr__ to slice out the phrase __because because because__ from the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
### Exercises: Level 3
1. 'Love is the best thing in this world. Some found their love and some are still looking for their love.' Count the number of word __love__ in this sentence.
2. Use __match()__ to count the number of all __because__ in the following sentence:__'You cannot end a sentence with because because because is a conjunction'__
3. Clean the following text and find the most frequent word (hint, use replace and regular expressions).
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and&@emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching'
```
4. Calculate the total annual income of the person by extracting the numbers from the following text. 'He earns 5000 euro from salary per month, 10000 euro annual bonus, 15000 euro online courses per month.'
🎉 CONGRATULATIONS ! 🎉
[<< Day 1](../readMe.md) | [Day 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)
// endsWith: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
// string.endsWith(substring)
letstring='Love is the best to in this world'
console.log(string.endsWith('world'))// true
console.log(string.endsWith('love'))// false
console.log(string.endsWith('in this world'))// true
// includes(): It takes a substring argument and it check if substring argument exists in the string. includes() returns a boolean. It checks if a substring exist in a string and it returns true if it exists and false if it doesn't exist.
// indexOf(): Takes takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1
// lastIndexOf(): Takes takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1
letstring='I love JavaScript. If you do not love JavaScript what else can you love.'
// 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.
letstring='love'
letpatternOne=/love/// with out any flag
letpatternTwo=/love/gi// g-means to search in the whole text, i - case insensitive
string.match(substring)
letstring='I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.match('love'))//
/*
output
["love",index:2,input:"I love JavaScript. If you do not love JavaScript what else can you love.",groups:undefined]
// 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).
- [Introdução a tipo de Dados](#introdução-a-tipo-de-dados)
- [Números](#números)
- [Strings](#strings)
- [Booleanos](#booleans)
- [Undefined](#undefined)
- [Null](#null)
- [Verificando Tipo de Dados](#checking-data-types)
- [Novamente Comentarios](#comments-again)
- [Variáveis](#variables)
- [💻 Dia 1: Exercícios](#-day-1-exercises)
- [Verificando Tipos de Dados](#verificando-tipos-de-dados)
- [Comentários novamente](#comentários-novamente)
- [Variáveis](#variáveis)
- [💻 Dia 1: Exercícios](#-dia-1-exercícios)
# 📔 Dia 1
## Introdução
**Parabéns** Em decidir participar dos 30 dias de JavaScript desafio. Neste desafio você aprenderá tudo que precisa para ser um JavaScript programador, e em general, todo o conceito de programaçao. No fim do desafio voce estará adquirindo o Certificado de conclusão dos 30DiasdeJavaScript desafio. Em caso de precisar de ajuda ou se preferir ajudar outros você pode entrar no [Grupo Telegram](https://t.me/ThirtyDaysOfJavaScript).
**Parabéns** Em decidir de participar do desafio 30DaysOfJavaScript. Neste desafio você aprenderá tudo que precisa para ser um programador JavaScript, e em general, todo o conceito de programação. No fim do desafio voce estará adquirindo o Certificado de conclusão do desafio 30DaysOfJavaScript. Em caso de precisar de ajuda ou se preferir ajudar outros você pode entrar no [Grupo Telegram](https://t.me/ThirtyDaysOfJavaScript).
**30DiasDeJavaScript** desafio é um guia tanto para iniciantes e Avançados JavaScript Desenvolvedores, Bem vindo ao JavaScript. JavaScript é a linguagem da internet. Eu me divirto em usar e ensinar JavaScript e eu acredito que voce fará tambem.
**30DaysOfJavaScript** desafio é um guia tanto para iniciantes e Avançados JavaScript Desenvolvedores, Bem vindo ao JavaScript. JavaScript é a linguagem da internet. Eu me divirto em usar e ensinar JavaScript e eu acredito que voce fará tambem.
Neste passo a passo do JavaScript Desafio, você aprenderá JavaScript, a mais popular linguagem de programação da história da humanindade.
Neste passo a passo do desafio JavaScript, você aprenderá JavaScript, a mais popular linguagem de programação da história da humanindade.
JavaScript é usado **_para adicionar interatividade aos websites, desenvolvimento de mobile apps, desktop aplicações, jogos_** e nos dias de hoje JavaScript pode ser usado para **_machine learning_** e **_AI_**.
**_JavaScript (JS)_** Teve um aumento na popularidade nos últimos anos e segue como a linguagem de programação líder por seis anos consecutivos e é a linguagem de programação mais usada no GitHub
@ -135,13 +135,13 @@ Sem conhecimentos prévios de programação é exigido para seguir este desafio.
Eu acredito que voce tem a motivação e o forte desejo de ser um desenvolvedor, um computador e internet. Se voce tem isso, então você tem tudo para iniciar.
## Instalando Node.js
## Instalação Node.js
Você pode não precisar do Node.js agora mas você precisará mais tarde. Instalação do [node.js](https://nodejs.org/en/).

Depois do download click duplo e intalar
Depois do download click duplo no ícone e intalar

@ -180,12 +180,12 @@ Windows/Linux:
Ctl+Shift+J
```


Depois de você abrir o console do Google Chrome, tente explorar os botões marcados. Nós vamos passar a maior parte do tempo no Console. O Console é o lugar onde vai seu código de JavaScript. O Console do Google Chrome V8 engine muda seu codigo de JavaScript para código de máquina.
Vamos escrever códigos de JavaScript no Google Chome console:


#### Escrevendo Código no console do Navegador
@ -201,7 +201,7 @@ Ctl+Shift+I
##### Console.log
Para escrever nosso primeiro código em JavaScript, vamos usar uma função já construída chamada**console.log()**. Nós passamos um argumento como dados de input, e a função mostra o output. Nós passamos `'Olá, Mundo!'` como dados de input ou argumento na função console.log().
Para escrever nosso primeiro código em JavaScript, vamos usar uma função built-it **console.log()**. Nós passamos um argumento como dados de input, e a função mostra o output. Nós passamos `'Olá, Mundo!'` como dados de input ou argumento na função console.log().
```js
console.log('Olá, Mundo!')
@ -211,7 +211,7 @@ console.log('Olá, Mundo!')
A funçao **`console.log()`** pode receber múltiplos parâmetros separados por vírgulas. A sintaxe é similar ao seguinte modo:**`console.log(param1, param2, param3)`**


```js
console.log('Olá', 'Mundo', '!')
@ -225,150 +225,143 @@ Parabéns! Você escreveu seu primeiro código de JavaScript usando _`console.lo
##### Comentários
Nós podemos adicionar comentários para nosso código. Comentários sao importantes para fazer o codigo ser fácil de ler e deixar observações no nosso código. JavaScript nao executa o partes com comentário no nosso código. No JavaScript, qualquer linha de texto começando com // em JavaScript é um comentário, e q
##### Comments
Nós podemos adicionar comentários para nosso código. Comentários são importantes para facilitar a leitura do código e deixar observações. O JavaScript não executa as partes com comentário no nosso código. No JavaScript, qualquer linha de texto começando com // é um comentário, e tudo anexo como isto `//` tambem é um comentário.
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**
**Exemplo: Comentário de linha única**
```js
// This is the first comment
// This is the second comment
// I am a single line comment
// Este é o primeiro comentário
// Este é o segundo comentário
// Eu sou um comentário de linha única
```
**Example: Multiline Comment**
**Exemplo: Comentários Várias Linhas**
```js
/*
This is a multiline comment
Multiline comments can take multiple lines
JavaScript is the language of the web
Isto é um comentário de várias linhas
Várias linhas de comentários.
JavaScript é a Linguagem da Web
*/
```
##### Sintaxe
##### 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.
Linguagens de programação são similares com a linguagem humana. Portugês ou qualquer outra linguagem usa palavras, frases, orações, períodos, e outras mais para criar uma mensagem com significado. A definição em Português de sintaxe é _ Estrutura essencial para que frases, orações e períodos façam sentido e sejam de fácil compreensão por parte do leitor_. A definição técnica é a estrutura de declarações em uma linguagem de computador. Linguagens de programação tem sintaxes. JavaScript é uma linguagem de programação como outras linguagens de programação tem sua própria sintaxe. Se nós nao escrevermos uma sintaxe que JavaScript entenda, diferentes tipos de errors aparecerá. Nós iremos explorar diferentes tipos de errors no JavaScript depois. Por enquanto, vamos ver sintaxes de errors.


I made a deliberate mistake. As a result, the console raises syntax errors. Actually, the syntax is very informative. It informs what type of mistake was made. By reading the error feedback guideline, we can correct the syntax and fix the problem. The process of identifying and removing errors from a program is called debugging. Let us fix the errors:
Eu fiz uma confusão proposital. Como resultado, criou vários errors. Na realidade, a sintaxe é muito informativa. Informa quais tipos de errors foi feito. lendo as mensagens do feedback de error, nós podemos corrigir a sintaxe e resolver o problema. O processo de identificar e remover errors de um programa é chamado de Debugging. Vamos resolver os errors:
```js
console.log('Hello, World!')
console.log('Hello, World!')
console.log('Olá, Mundo!')
console.log('Olá, Mundo!')
```
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:**
Até agora, nós vimos como exibir texto usando o _`console.log()`_. Se estamos imprimindo texto ou string usando _`console.log()`_, o texto tem que estar dentro de uma aspa simples, aspas duplas, ou crase.
**Exemplo:**
```js
console.log('Hello, World!')
console.log("Hello, World!")
console.log('Olá, Mundo!')
console.log("Olá, Mundo!")
console.log(`Hello, World!`)
```
#### Arithmetics
#### Aritimética
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.
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.
Agora, vamos praticar escrevendo mais códigos JavaScript usando _`console.log()`_ no console do Google Chrome para números e tipos de dados.
Em adição ao texto, nós podemos tamem fazer calculos matemáticos usando javaSCript. Vamos fazer calculos simples a seguir.
É possivel escrever códigos JavaScript no console do Google Chome diretamente sem o função **_`console.log()`_** Entretanto, está incluso nesta introdução porque maior parte deste desafio pode ocorrer no editor de texto onde o uso de funcões pode ser mantario. Você pode brincar diretamente com ins
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 dias de JavaScript challenge, we will be using Visual Studio Code.
Nós podemos escrever nosso código no console do navegador. mas isso nao é usado para grandes projetos. No anbiente real de trabalho, desenvolvedores usam diferentes editores para escrever seus códigos. Neste desafio 30 dias de JavaScript, nós iremos utilizar o Visual Studio Code.
#### Installing Visual Studio Code
#### Instalando o 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 é editor de texto open-source muito popular. Eu poderia recomendar o [download Visual Studio Code](https://code.visualstudio.com/), mas se você está familiarizado com outro editor, sinta livre para seguir oque você tem.


If you installed Visual Studio Code, let us start using it.
Se você instalou o Visual Studio Code, Vamos começar usando-o.
#### How to Use Visual Studio Code
#### Como Usar o Visual Studio Code
Open the Visual Studio Code by double-clicking its icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons.
Abra o Visual Studio Code clicando duas vezes com o mouse no ícone. Quando abrir, você terá esta interface. Tente interagir com os ícones rotulados.
JavaScript can be added to a web page in three different ways:
JavaScript pode ser adicionado para uma página na internet em três diferentes maneiras:
- **_Inline script_**
- **_Internal script_**
- **_External script_**
- **_Multiple External scripts_**
- **_Script em linha_**
- **_Script Interno_**
- **_Script Externo_**
- **_Múltiplos Scripts Externos_**
The following sections show different ways of adding JavaScript code to your web page.
As diferentes sessões mostra diferentes maneiras de adicionar códigos JavaScript para sua página na 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/).
Crie uma pasta do projeto no seu desktop ou em qualquer localização, nomeie de 30DaysOfJS e crie um **_`index.html`_** documento na sua pasta do projeto.
Então copie os seguintes códigos e abra-o no navegador, por exemplo [Chrome](https://www.google.com/chrome/).
```html
<!DOCTYPE html>
<htmllang="en">
<head>
<title>30DaysOfScript:Inline Script</title>
<title>30DaysOfScript: Script em linha</title>
</head>
<body>
<buttononclick="alert('Welcome to 30DiasDeJavaScript!')">Click Me</button>
<buttononclick="alert('Welcome to 30DaysOfScript!')">Clique</button>
</body>
</html>
```
Agora, você escreveu seu primeiro script em linha. Nós podemos criar uma mensagem pop up usando o _`alert()`_ função built-it
Now, you just wrote your first inline script. We can create a pop up alert message using the _`alert()`_ built-in function.
### Internal Script
### Script Interno
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.
O script interno pode ser escrito no _`head`_ ou _`body`_, mas é preferível colocar no body do documento HTML.
```html
<!DOCTYPE html>
<htmllang="en">
<head>
<title>30DaysOfScript:Internal Script</title>
<title>30DaysOfScript: Script Interno</title>
<script>
console.log('Welcome to 30DiasDeJavaScript')
console.log('Welcome to 30DaysOfJavaScript')
</script>
</head>
<body></body>
</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()`.
Isto é como nós escrevemos scripts internos na maioria das vezes. Escrevemos o código de JavaScript na sessão body é a mais preferida opção. Abra o console do navegador e veja o output do`console.log()`.
```html
<!DOCTYPE html>
@ -377,72 +370,74 @@ This is how we write an internal script most of the time. Writing the JavaScript
<title>30DaysOfScript: Internal Script</title>
</head>
<body>
<buttononclick="alert('Welcome to 30DiasDeJavaScript!');">Click Me</button>
<buttononclick="alert('Welcome to 30DaysOfJavaScript!');">Click</button>
<script>
console.log('Welcome to 30DiasDeJavaScript')
console.log('Welcome to 30DaysOfJavaScript')
</script>
</body>
</html>
```
Open the browser console to see the output from the`console.log()`.
Abra o console do navegador e veja o output do`console.log()`.


### External Script
### Script Externo
Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body.
First, we should create an external JavaScript file with .js extension. All files ending with .js extension 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.
Similar com o script interno, o link do script externo pode estar no header ou body, mas é mais indicado colocar no body do documento.
Primeiro, nós podemos criar scripts externos de JavaScript com a .js extensão. Todos os arquivos terminados com a .js extensão são JavaScript documentos. Crie uma pasta nomeada Introdução.js dentro do diretório do projeto e escreva o seguinte código e copie o link do arquivo .js no bottom do body.
<!-- 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 -->
<!-- JavaScript link externo pode estar no header ou no body -->
<!-- Antes do fechamento da tag do body é o lugar recomendado para colocar o script do JavaScript externo -->
<scriptsrc="introduction.js"></script>
</body>
</html>
```
Open the browser console to see the output of the`console.log()`.
Abra o console do navegador para ver o output do`console.log()`.
### Multiple External Scripts
### Múltiplos Scripts Externos
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.
Nós tambem podemos colocar o link de vários arquivos externos de JavaScript em uma página web.
Crie um `helloworld.js` documento dentro da pasta 30DaysOfJS e escreva o seguinte código.
```js
console.log('Hello, World!')
console.log('Olá, Mundo!')
```
```html
<!DOCTYPE html>
<htmllang="en">
<head>
<title>Multiple External Scripts</title>
<title>Múltiplos Scripts Externo</title>
</head>
<body>
<scriptsrc="./helloworld.js"></script>
@ -451,28 +446,27 @@ console.log('Hello, World!')
</html>
```
_Your main.js file should be below all other scripts_. It is very important to remember this.
_Seu arquivo main.js deve estar abaixo de todos os outros scripts_. E isto é muito importante de relembrar


## Introduction to Data types
## Introdução a tipo de Dados
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_.
Em JavaScript e tambem em outras linguagens de programação, existem vários tipos de dados. Os seguintes são tipos de dados primitivos do JavaScript: _String, Number, Boolean, undefined, Null_, and _Symbol_.
### Numbers
### Números
- Integers: Integer (negative, zero and positive) numbers
Example:
- Integers: Inteiros (Negativo, zero e positivos) números
Examplo:
... -3, -2, -1, 0, 1, 2, 3 ...
- Float-point numbers: Decimal number
Example
- Float-point numbers: Números decimais.
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
### Strings
A collection of one or more characters between two single quotes, double quotes, or backticks.
Uma coleção de um ou mais caracteres entre duas aspas simples, aspas duplas, ou crase.
**Example:**
**Examplo:**
```js
'a'
@ -489,11 +483,11 @@ A collection of one or more characters between two single quotes, double quotes,
### Booleans
A boolean value is either True or False. Any comparisons returns a boolean value, which is either true or false.
Um valor boleano ou é verdadeiro ou falso. Qualquer comparação retorna um valor booleano, que pode ser entre verdadeiro ou falso.
A boolean data type is either a true or false value.
Um tipo de dado boleanno é verdadeiro ou um valor falso
**Example:**
**Examplo:**
```js
true // if the light is on, the value is true
@ -502,7 +496,7 @@ false // if the light is off, the value is false
### 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.
Em JavaScript, se nós não atribuirmos um valor a uma variável, o valor é undefined. Em adição a isto, se uma funcção não está retornando nada, ela retorna undefined
```js
let firstName
@ -511,15 +505,15 @@ console.log(firstName) // undefined, because it is not assigned to a value yet
### Null
Null in JavaScript means an empty value.
Null em JavaScript significa um valor vazio.
```js
let emptyValue = null
let valorVazio = null
```
## Checking Data Types
## Verificando Tipos de Dados
To check the data type of a certain variable, we use the **typeof** operator. See the following example.
Para verificar o tipo de dado de uma determinada variável, nós usamos o operador **typeof**. Veja o seguinte exemplo.
```js
console.log(typeof 'Asabeneh') // string
@ -529,45 +523,45 @@ console.log(typeof null) // object type
console.log(typeof undefined) // undefined
```
## Comments Again
## Comentários novamente
Remember that commenting in JavaScript is similar to other programming languages. Comments are important in making your code more readable.
There are two ways of commenting:
Lembre que comentando no JavaScript é similar à outras linguagens de programação. Comentários são importantes em fazer mais fácil a leitura do seu código.
Existe dois modos de comentar:
- _Single line commenting_
- _Multiline commenting_
- _Comentando em linha única_
- _Comentando em várias linhas_
```js
// commenting the code itself with a single comment
// let firstName = 'Asabeneh'; single line comment
// let lastName = 'Yetayeh'; single line comment
// Comentando o código com um único comentário
// let firstName = 'Asabeneh'; Comentando em linha única_
// let lastName = 'Yetayeh'; Comentando em linha única_
```
Multiline commenting:
Comentando em várias linhas:
```js
/*
let location = 'Helsinki';
let age = 100;
let isMarried = true;
This is a Multiple line comment
Isto é um comentário em linha única
*/
```
## Variables
## Variáveis
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.
Variáveis são _containers_ de dados. Variáveis são usadas para _armazenar_ dados na memória alocada. Quando variáveis são declaradas, uma memória alocada é reservada. Quando uma variável é atribuída para um valor (dados), espaço na memória irá ser preenchido com aqueles dados. Para declarar uma variável, nós usamos as palavras-chaves _var_, _let_, ou _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.
Para uma variável que muda com o tempo, nós usamos _let_. Se os dados não vão mudar, nós usamos _const_. Por exemplo, PI, nome de país, gravidade não muda, e nós podemos usar _const_. Nós não vamos usar var neste desafio e eu nao recomendo usa-lo. Nós vamos falar mais sobre var, let, e const em detalhes em outras sessões (scope). Por enquanto, a explicação acima é suficiente.
A valid JavaScript variable name must follow the following rules:
Um nome de variável em JavaScript apenas segue a seguinte regra:
- A JavaScript variable name should not begin with a number.
- A JavaScript variable name does not allow special characters except dollar sign and underscore.
- A JavaScript variable name follows a camelCase convention.
- A JavaScript variable name should not have space between words.
- Um nome de variável não deverá começar com um número.
- Um nome de variável não pode permitir caracteres especiais exceto o sinal do dólar e underscore.
- Um nome de variável segue a convenção camelCase.
- Um nomede variável não deve ter espaços entre as palavras.
The following are examples of valid JavaScript variables.
Os seguintes exemplos são de variáveis válidas em JavaScript.
```js
firstName
@ -591,9 +585,9 @@ 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(camelWithOneHump). We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about classes and objects in other section.
A primeira e a segunda variável na lista segue a convenção camelCase de declaração no JavaScript. Neste material, nós vamos usar variáveis em camelCase (camelWithOneHump). Nós usamos CamelCase (CamelWithTwoHump) para declarar classes, nós vamos discutir sobre classes e objetos em outras sessões.
Example of invalid variables:
Exemplo de variáveis invalidas:
```js
first-name
@ -601,24 +595,24 @@ Example of invalid variables:
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).
Vamos declarar variáveis com diferentes tipos de dados. Para declarar uma variável, nós precisamos usar as palavras-chaves _let_ ou _const_ antes de um nome de variável. Após o nome da variável, nós escrevemos um sinal de igual (operador de atribuição), e um valor (dados atribuidos).
```js
// Syntax
// Sintaxe
let nameOfVariable = value
```
The nameOfVriable is the name that stores different data of value. See below for detail examples.
O nomeDaVariavel é o nome que armazena diferente tipos de dados. Veja abaixo exemplos para mais detalhes.
**Examples of declared variables**
**Exemplos de variáveis declaradas**
```js
// Declaring different variables of different data types
let firstName = 'Asabeneh' // first name of a person
let lastName = 'Yetayeh' // last name of a person
let country = 'Finland' // country
let city = 'Helsinki' // capital city
let age = 100 // age in years
// Declarando diferentes variáveis de diferentes tipos de dados
let firstName = 'Asabeneh' // primeiro nome de uma pessoa
let lastName = 'Yetayeh' // ultimo nome de uma pessoa
let country = 'Finland' // país
let city = 'Helsinki' // capital da cidade
let age = 100 // Idade
let isMarried = true
console.log(firstName, lastName, country, city, age, isMarried)
@ -629,11 +623,11 @@ Asabeneh Yetayeh Finland Helsinki 100 true
```
```js
// Declaring variables with number values
let age = 100 // age in years
const gravity = 9.81 // earth gravity in m/s2
const boilingPoint = 100 // water boiling point, temperature in °C
const PI = 3.14 // geometrical constant
// Declarando variáveis com o valor numérico
let age = 100 // idade
const gravity = 9.81 // gravidade na terra em m/s2
const boilingPoint = 100 // ponto de ebulição da água, temperatura em °C
// Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble
// Variáveis tambem podem ser declaradas em uma linha separadas por uma vírgula, entretanto eu recomento usar a separação por linha para facilitar a leitura do código
let name = 'Asabeneh', job = 'teacher', live = 'Finland'
console.log(name, job, live)
```
@ -651,32 +645,30 @@ console.log(name, job, live)
Asabeneh teacher Finland
```
When you run _index.html_ file in the 01-Day folder you should get this:
Quando você executa o arquivo _index.html_ na pasta dia-1 você deve conseguir isto:


🌕 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.
🌕 Você é incrivel! Você acaba de completar o desafio do dia 1 e você está no seu caminho para a grandeza. Agora faça alguns exercícios para seu cérebro e músculos.
# 💻 Day 1: Exercises
# 💻 Dia 1: Exercícios
1. Write a single line comment which says, _comments can make code readable_
2. Write another single comment which says, _Welcome to 30DiasDeJavaScript_
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
5. Create datatypes.js file and use the JavaScript **_typeof_** operator to check different data types. Check the data type of each variable
6. Declare four variables without assigning values
7. Declare four variables with assigned values
8. Declare variables to store your first name, last name, marital status, country and age in multiple lines
9. Declare variables to store your first name, last name, marital status, country and age in a single line
10. Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to the browser console.
1. Escreva um comentário de linha única que diga, _comentários faz seu código ser fácil de ler_
2. Escreva outro comentário de linha única que diga, _Welcome to 30DaysOfJavaScript_
3. Escreva um comentário de várias linhas que diga, _comentários faz seu código ser fácil de ler, fácil de reusar_ _e informátivo_
4. Crie um arquivo variavel.js e declare variáveis e atribua uma string, boolean, undefined e null
5. Crie um arquivo tiposdedados.js e use o JavaScript **_typeof_** operador para verificar diferentes tipos de dados. Verifique o tipo de dado de cada variável
6. Declare quatro variáveis sem atribuir valores
7. Declare quatro variáveis e atribuir valores
8. Declare variáveis para armazenar seu primeiro nome, ultimo nome, estado civil, país e idade em multiplas linhas
9. Declare variáveis para armazenar seu primeiro nome, ultimo nome, estado civil, país e idade em uma única linha
10. Declare duas variáveis _minhaIdade_ e _suaIdade_ e atribua valores iniciais e mostre no console do navegador.
Основное правило, мы не сравниваем непримитивные типы данных. Не сравнивайте массив, функцию или объект.
Непримитивные значения называются ссылочными типами, поскольку они сравниваются по значению, а не по значению. Два объекта строго равны, если они ссылаются на один и тот же базовый объект.
Непримитивные значения называются ссылочными типами, потому что они сравниваются по ссылке, а не по значению. Два объекта строго равны, если они ссылаются на один и тот же базовый объект.
const randNum = Math.random(); // создает случайное число от 0 до 0,999999
const randNum = Math.random(); // создаёт случайное число от 0 до 0,999999
console.log(randNum);
// Давайте создадим случайное число от 0 до 10
const num = Math.floor(Math.random() * 11); // создает случайное число от 0 до 10
const num = Math.floor(Math.random() * 11); // создаёт случайное число от 0 до 10
console.log(num);
// Абсолютное значение
@ -256,10 +256,10 @@ let randomNum = Math.random(); // генерирует от 0 до 0,999
let randomNum = Math.random(); // генерирует от 0 до 0,999
let numBtnZeroAndTen = randomNum * 11;
console.log(numBtnZeroAndTen); // это дает: мин 0 и макс 10.99
console.log(numBtnZeroAndTen); // это даёт: мин 0 и макс 10.99
let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen);
console.log(randomNumRoundToFloor); // это дает от 0 до 10
console.log(randomNumRoundToFloor); // это даёт от 0 до 10
```
## Строки
@ -306,7 +306,7 @@ Asabeneh Yetayeh
#### Конкатенация с использованием оператора сложения
Конкатенация с использованием оператора сложения - старый способ. Этот способ объединения утомителен и подвержен ошибкам. Полезно знать, как объединить таким способом, но я настоятельно рекомендую использовать второй способ.
Конкатенация с использованием оператора сложения - старый способ. Этот способ объединения утомителен и подвержен ошибкам. Полезно знать, как объединить таким способом, но я настоятельно рекомендую использовать шаблонные строки ES6.
```js
// Объявление разных переменных разных типов данных
@ -350,7 +350,7 @@ console.log(paragraph);
#### Перенос последовательности в строке
В JavaScript и других языках программирования, после некоторых символов есть перенос - последовательности. Давайте посмотрим на наиболее распространенные escape-символы:
В JavaScript и других языках программирования, после некоторых символов есть перенос - последовательности. Давайте посмотрим на наиболее распространённые escape-символы:
- `\n` - Новая строка
- `\t` - Таб означает (8 пробелов)
@ -375,7 +375,7 @@ console.log("The saying 'Seeing is Believing' is't correct in 2020");
#### Шаблонные литералы (Шаблонные строки)
Чтобы создать строку шаблона, мы используем два обратных ключа. Мы можем вставить данные как выражение внутри строки шаблона. Чтобы ввести данные, мы заключаем выражение в фигурную скобку (`{}`), за которой следует знак `$`. Смотрите синтаксис ниже.
Чтобы создать строку шаблона, мы используем два обратных ключа. Мы можем вставить данные как выражение внутри строки шаблона. Чтобы ввести данные, мы заключаем выражение в фигурную скобку (`{}`), предшествует которой знак `$`. Смотрите синтаксис ниже.
```js
// Синтаксис
@ -440,7 +440,7 @@ console.log(`${a} is greater than ${b}: ${a > b}`);
console.log(firstName.length); // 8
```
2. _Доступ к символам в строке_: мы можем получить доступ к каждому символу в строке, используя его индекс. В программировании отсчет начинается с 0. Первый индекс строки равен нулю, а последний индекс равен одному минус длина строки.
2. _Доступ к символам в строке_: мы можем получить доступ к каждому символу в строке, используя его индекс. В программировании отсчёт начинается с 0. Первый индекс строки равен нулю, а последний индекс равен одному минус длина строки.

@ -541,7 +541,7 @@ console.log(`${a} is greater than ${b}: ${a > b}`);
15. `concat()`: он принимает много подстрок и создает конкатенацию.
15. `concat()`: он принимает множество подстрок и конкатенирует их.
```js
string.concat(substring, substring, substring);
@ -693,7 +693,7 @@ console.log(`${a} is greater than ${b}: ${a > b}`);
console.log(country.startsWith("land")); // false
```
17. `endsWith`: он принимает подстроку в качестве аргумента и проверяет, начинается ли строка с указанной подстроки. Возвращает логическое значение (true или false).
17. `endsWith`: он принимает подстроку в качестве аргумента и проверяет, заканчивается ли строка указанной подстрокой. Возвращает логическое значение (true или false).
```js
string.endsWith(substring);
@ -755,14 +755,14 @@ console.log(`${a} is greater than ${b}: ${a > b}`);
Давайте извлечем числа из текста, используя регулярное выражение. Это не раздел регулярных выражений, не паникуйте, мы рассмотрим регулярные выражения в другом разделе.
Давайте извлечём числа из текста, используя регулярное выражение. Это не раздел регулярных выражений, не паникуйте, мы рассмотрим регулярные выражения в другом разделе.
```js
let txt =
"In 2019, I run 30 Days of Python. Now, in 2020 I super exited to start this challenge";
let regEx = /\d+/;
// d сперенос-символом означает, что d не является нормальным d, вместо этого действует цифра
// d сescape-символом означает, что d - не просто символ d, а обозначает цифру
// + означает одно или несколько цифр,
// если после этого есть g, значит глобальный, ищите везде.
@ -785,7 +785,7 @@ console.log(`${a} is greater than ${b}: ${a > b}`);
### Проверка типов данных
- Проверка типов данных: чтобы проверить тип данных определенного типа данных, мы используем `typeof` и также меняем один тип данных на другой.
- Проверка типов данных: чтобы проверить тип данных определённого типа данных, мы используем `typeof` и также меняем один тип данных на другой.
**Пример:**
@ -889,7 +889,7 @@ let numInt = parseInt(num);
console.log(numInt); // 9
```
🌕 Ты обалденный. Вы только что завершили 2-й день испытаний, и вы в двух шагах от своего пути к успеху. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц.
🌕 Ты молодец. Ты только что завершил 2-й день испытаний, и ты в двух шагах от своего пути к успеху. Теперь сделай несколько упражнений для мозга и твоих мышц.
## 💻 День 2: Упражнения
@ -905,19 +905,19 @@ console.log(numInt); // 9
8. Проверьте, содержит ли строка слово **Script**, используя метод `includes()`
9. Разбейте **строку** на **массив**, используя метод `split()`
10. Разбить строку 30 Days Of JavaScript в пространстве с помощью метода `split()`
11. «Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon» **разбивают** строку на запятую и заменяют ее на массив.
11. «Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon» **разбейте** строку где разделитель - запятая и замените её на массив.
12. Измените 30 Days Of JavaScript на 30 Days Of Python, используя метод `replace()`.
13. Что такое символ в индексе 15 в строке «30 Days Of JavaScript», используйте метод `charAt()`.
14. Что такое код символа J в строке «30 Days Of JavaScript» с использованием `charCodeAt()`
13. Какой символ в индексе 15 в строке «30 Days Of JavaScript», используйте метод `charAt()`.
14. Какой код символа J в строке «30 Days Of JavaScript» с использованием `charCodeAt()`
15. Используйте `indexOf`, чтобы определить позицию первого вхождения за 30 Days Of JavaScript
16. Используйте `lastIndexOf`, чтобы определить позицию последнего вхождения в 30 Days Of JavaScript.
17. Используйте `indexOf`, чтобы найти позицию первого вхождения слова **потому что** в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что, потому что это соединение»**
18. Используйте `lastIndexOf`, чтобы найти позицию последнего вхождения слова **потому что** в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что потому что это соединение»**
19. Используйте `search`, чтобы найти позицию первого вхождения слова **потому что** в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что потому что это соединение»**
20. Используйте `trim()`, чтобы удалить, если в начале и конце строки есть конечные пробелы. Например, «30 Days Of JavaScript».
21. Используйте метод `launchWith()` со строкой _30 Days Of JavaScript_, чтобы сделать результат верным
22. Используйте метод `setsWith()` со строкой _30 Days Of JavaScript_, чтобы сделать результат верным
23. Используйте метод `match()`, чтобы найти все за 30 Days Of JavaScript
20. Используйте `trim()`, чтобы удалить все пробелы в начале и конце строки. Например, «30 Days Of JavaScript».
21. Используйте метод `startsWith()` со строкой _30 Days Of JavaScript_, чтобы сделать результат верным
22. Используйте метод `endsWith()` со строкой _30 Days Of JavaScript_, чтобы сделать результат верным
23. Используйте метод `match()`, чтобы найти все "а" в "30 Days Of JavaScript"
24. Используйте `concat()` и объедините «30 Days» и «JavaScript» в одну строку «30 Days Of JavaScript»
25. Используйте метод `repeat()`, чтобы напечатать 30 Days Of JavaScript 2 раза
@ -937,10 +937,10 @@ console.log(numInt); // 9
3. Проверьте, точно ли `typeof` '10' равен 10. Если нет, сделайте его точно равным.
4. Убедитесь, что `parseFloat('9.8')` равен 10, если не равен точно 10.
5. Проверьте, найдено ли 'on' как в Python, так и в жаргоне
6. Я надеюсь, что этот курс не полон жаргона. Проверьте, находится ли _jargon_ в предложении.
5. Проверьте, найдено ли 'он' как в Питон, так и в жаргоне
6. Я надеюсь, что этот курс не полон жаргона. Проверьте, находится ли _жаргон_ в предложении.
7. Сгенерируйте случайное число от 0 до 100 включительно.
8. Генерация случайного числа от 50 до 100 включительно.
8. Сгенерируйте случайное число от 50 до 100 включительно.
9. Сгенерируйте случайное число от 0 до 255 включительно.
10. Получите доступ к символам строки «JavaScript», используя случайное число.
11. Используйте `console.log()` и управляющие символы для печати следующего шаблона.
@ -957,9 +957,9 @@ console.log(numInt); // 9
### Упражнения: уровень 3
1. «Любовь - лучшая вещь в этом мире. Некоторые нашли свою любовь, а некоторые все еще ищут свою любовь. Подсчитайте количество слов любви в этом предложении.
2. Используйте `match()`, чтобы сосчитать число все потому, что в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что, потому что это соединение»**
3. Очистите следующий текст и найдите наиболее часто встречающееся слова (подсказка, используйте замену и регулярный экспресс).
1. «Любовь - лучшая вещь в этом мире. Некоторые нашли свою любовь, а некоторые все ещё ищут свою любовь. Подсчитайте количество слов "любовь" в этом предложении.
2. Используйте `match()`, чтобы сосчитать число все **"потому что"** в следующем предложении: **«Вы не можете закончить предложение, потому что, потому что, потому что это соединение»**
3. Очистите следующий текст и найдите наиболее часто встречающееся слова (подсказка, используйте замену и регулярные выражения).
Нужно хорощо помнить эти истинные и ложные значения. В следующем разделе мы будем использовать их с условиями для принятия решения.
Нужно хорошо помнить эти истинные и ложные значения. В следующем разделе мы будем использовать их с условиями для принятия решения.
## Undefined
Если мы объявим переменную и не назначим значение, оно будет неопределенным. В дополнение к этому, если функция не возвращает значение, оно будет неопределенным.
Если мы объявим переменную и не назначим значение, оно будет неопределённым (undefined). В дополнение к этому, если функция не возвращает значение, оно будет неопределённым.
Попытайтесь понять приведенные выше сравнения с некоторой логикой. Запоминать без какой-либо логики может быть сложно.
JavaScript - это своего рода проводной язык программирования. Код JavaScript запускается и дает вам результат, но если вы не разбираетесь в нем, это может быть нежелательным результатом.
Попытайтесь понять приведённые выше сравнения с некоторой логикой. Запоминать без какой-либо логики может быть сложно.
JavaScript - это своего рода проводной язык программирования. Код JavaScript запускается и даёт вам результат, но если вы не разбираетесь в нем, это может быть нежелательным результатом.
По практическому правилу, если значение не верно с`==`, оно не будет равно `===`. Использование `===` более безопасно, чем использование `==`. Следующая [ссылка](https://dorey.github.io/JavaScript-Equality-Table/) имеет исчерпывающий список сравнения типов данных.
@ -273,7 +273,7 @@ let isMarried = !false; // true
console.log(count); // 1
```
Мы используем большую часть времени после приращения. По крайней мере, вы должны помнить, как использовать постинкрементный оператор.
Мы используем большую часть времени пост-инкремент. По крайней мере, вы должны помнить, как использовать постинкрементный оператор.
### Оператор декремента
@ -371,18 +371,18 @@ console.log(number);
Метод `confirm()` отображает диалоговое окно с указанным сообщением, а также кнопки "ОК" и "Отмена".
Окно подтверждения часто используется, чтобы запросить у пользователя разрешение на что-либо. Окно `confirm()` принимает строку в качестве аргумента.
Нажатие "ОК" дает значение `true`, нажатие кнопки "Отмена" дает значение `false`.
Нажатие "ОК" даёт значение `true`, нажатие кнопки "Отмена" даёт значение `false`.
```js
const agree = confirm("Are you sure you like to delete? ");
console.log(agree); // результат будет true или false в зависимости от того, что вы нажимаете в диалоговом окне
```
These are not all the window methods we will have a separate section to go deep into window methods.
Это не все оконные методы , в курсе представлены отдельные разделы для того чтобы погрузиться глубже в оконные методы.
## Объект Date
Время это важная вещь. Нам нравится знать время определенного действия или события. В JavaScript текущее время и дата создаются с использованием JavaScript Date Object. Объект, который мы создаем с использованием объекта Date, предоставляет множество методов для работы с датой и временем. Методы, которые мы используем для получения информации о дате и времени из значений объекта даты, начинаются со слова _get_, поскольку они предоставляют информацию.
Время это важная вещь. Нам нравится знать время определённого действия или события. В JavaScript текущее время и дата создаются с использованием JavaScript Date Object. Объект, который мы создаём с использованием объекта Date, предоставляет множество методов для работы с датой и временем. Методы, которые мы используем для получения информации о дате и времени из значений объекта даты, начинаются со слова _get_, поскольку они предоставляют информацию.
- `getFullYear()`,
- `getMonths()`,
@ -399,7 +399,7 @@ These are not all the window methods we will have a separate section to go deep
### Создание объекта времени
Однажды мы создаем объект времени. Объект времени предоставит информацию о времени. Давайте создадим объект времени
Однажды мы создаём объект времени. Объект времени предоставит информацию о времени. Давайте создадим объект времени
```js
const now = new Date();
@ -410,7 +410,7 @@ console.log(now); // Sat Jan 04 2020 00:56:41 GMT+0200 (Eastern European Standar
### Получение года
Давайте извлечем или получим полный объект времени.
Давайте извлечем или получим полный год из объекта времени.
🌕 У вас есть безграничная энергия! Вы только что выполнили 3-й день испытаний, и вы на три шага на пути к успеху. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц.
🌕 У вас безграничная энергия! Вы только что выполнили 3-й день испытаний, и вы на три шага на пути к успеху. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц.
3. Получите длину и ширину, используя подсказку, и вычислите площадь прямоугольника (площадь = длина х ширина и периметр прямоугольника (периметр = 2 х (длина + ширина))
4. Получите радиус, используя подсказку, и вычислите площадь круга (площадь = pi x r x r) и окружность круга (c = 2 x pi x r), где pi = 3.14.
3. Получите длину и ширину, используя prompt, и вычислите площадь прямоугольника (площадь = длина х ширина и периметр прямоугольника (периметр = 2 х (длина + ширина))
4. Получите радиус, используя prompt, и вычислите площадь круга (площадь = pi x r x r) и окружность круга (c = 2 x pi x r), где pi = 3.14.
5. Рассчитайте наклон, x-пересечение и y-пересечение y = 2x -2
6. Наклон (m = y2-y1 / x2-x1). Найти наклон между точкой (2, 2) и точкой (6,10)
7. Сравните наклон двух приведенных выше вопросов.
7. Сравните наклон двух приведённых выше вопросов.
8. Рассчитайте значение y (y = x ^ 2 + 6x + 9). Попробуйте использовать разные значения х и выяснить, при каком значении ху 0.
9. Напишите скрипт, который побудит пользователя вводить часы и ставку за час. Рассчитать зарплату человека?
9. Напишите скрипт,который предлагает пользователю ввести часы и ставку за час. Рассчитать зарплату человека?
13. Используя подсказку, укажите год рождения пользователя и, если ему исполнилось 18 лет, разрешите ему ехать, если он не скажет пользователю подождать определенное количество лет.
13. Используя подсказку, укажите год рождения пользователя и, если ему исполнилось 18 лет, разрешите ему ехать, если он не скажет пользователю подождать определённое количество лет.
```sh
Введите год рождения: 1995
Вам 25. Вы достаточно взрослый, чтобы водить
Введите год рождения: 2005
Вам 15. Вам будет разрешено водить после 3 лет.
Вам 15. Вам будет разрешено водить через 3 года.
```
14. Напишите скрипт, который предложит пользователю ввести количество лет. Подсчитайте, сколько секунд человек может прожить. Предположим, кто-то живет всего сто лет
14. Напишите скрипт, который предложит пользователю ввести количество лет. Подсчитайте, сколько секунд человек может прожить. Предположим, кто-то живёт всего сто лет
Переключатель является альтернативой для `if else if else else`.
Оператор `switch` начинается с ключевого слова `switch`, за которым следуют скобки и блок кода. Внутри блока кода у нас будут разные случаи. Case case запускается, если значение в скобках оператора `switch` совпадает с case vale. Перерыв должен закончиться, и он не снижается после того, как условие выполнено. Блок по умолчанию выполняется, если все случаи не удовлетворяют условию.
Оператор `switch` начинается с ключевого слова `switch`, за которым следуют скобки и блок кода. Внутри блока кода у нас будут разные случаи (case). Блок case выполняется, если значение в скобках оператора `switch` совпадает со значением case. Операртор `break` служит для прерывания выполнения, чтобы выполнение кода не прекратилось после выполнения условия. Блок `default` выполняется, если все случаи не удовлетворяют условию.
```js
switch (caseValue) {
@ -242,7 +242,7 @@ switch (day) {
### Тернарный оператор
Другой способ написания условных выражений - использование тернарных операторов. Мы рассмотрели это в других разделах, но мы также должны упомянуть об этом здесь.
Другой способ написания условных выражений - использование тернарных операторов. Мы уже рассматривали этот способ в других разделах, но нам следует также упомянуть о нем здесь.
```js
let isRaining = true;
@ -257,7 +257,7 @@ isRaining
### Упражнения: уровень 1
1. Получить пользовательский ввод с помощью `prompt("Введите свой возраст:")`. Если пользователю 18 лет или больше, оставьте отзыв: вы достаточно взрослый, чтобы ездить, но если нет, то 18 - отзывайте, чтобы ждать те годы, которые он должен был ждать.
1. Получить пользовательский ввод с помощью `prompt("Введите свой возраст:")`. Если пользователю 18 лет или больше, вывести сообщение: вы достаточно взрослый, чтобы ездить, но если меньше 18 - выведете сообщение,в котором говорится что нужно подождать определённое количество лет, чтобы водить машину.
```sh
Введите свой возраст: 30
@ -267,14 +267,14 @@ isRaining
Вам осталось 3 года до вождения.
```
2. Сравните значения myAge и yourAge, используя _if… else_. На основе сравнения журнала для консоли, кто старше (я или вы). Используйте `prompt("Введите свой возраст:")`, чтобы получить возраст в качестве входных данных.
2. Сравните значения myAge и yourAgeс помощью if ... else. На основе сравнения выведите результат в консоль, указав, кто старше (я или вы). Используйте prompt("Enter your age:") для получения возраста в качестве входных данных.
```sh
Введите свой возраст: 30
Ты на 5 лет старше меня.
```
3. Если a больше, чем b, вернуть «a больше, чем b», иначе «a меньше, чем b». Попробуй реализовать в пути
3. Если a больше, чем b, вернуть «a больше, чем b», иначе «a меньше, чем b». Попробуйте реализовать это различными способами:
- используя if else
- тернарный оператор.
@ -288,26 +288,25 @@ isRaining
4 больше 3
```
4. Четные числа делятся на 2, а остаток равен нулю. Как проверить, является ли число четным или нет с помощью JavaScript?
4. Чётные числа делятся на 2, а остаток равен нулю. Как проверить, является ли число чётным или нет с помощью JavaScript?
```sh
Введите число: 2
2 - четное число
2 - чётное число
Введите число: 9
9 является нечетным числом.
9 является нечётным числом.
```
### Упражнения: уровень 2
1. Напишите код, который может дать оценку студентам в соответствии с их оценками:
1. Напишите код, который может дать оценку студентам в соответствии с их баллами:
- 80-100, A
- 70-89, B
- 70-79, B
- 60-69, C
- 50-59, D
- 0-49, F
2. Проверьте, является ли сезон осенью, зимой, весной или летом.
Если пользовательский ввод:
2. Проверьте, является ли сезон: осенью, зимой, весной или летом. Если пользователь ввёл :
В этом пошаговом руководстве вы изучите JavaScript, самый популярный язык программирования в истории человечества.
Вы используете JavaScript **_для добавления интерактивности на веб-сайты, для разработки мобильных приложений, настольных приложений, игр_**, и в настоящее время JavaScript можно использовать для **_машинногообучения_** и **_AI_**.
**_JavaScript (JS)_** вырос в популярности в последние годы и был ведущим языком программирования в течение четырех лет подряд и является наиболее используемым языком программирования на Github.
**_JavaScript (JS)_** вырос в популярности в последние годы и был ведущим языком программирования в течение четырёх лет подряд и является наиболее используемым языком программирования на Github.
## Требования
@ -90,11 +90,11 @@
### Установка Node.js
Возможно, вам это не нужно прямо сейчас, но может понадобиться позже. Устанавить [node.js](https://nodejs.org/en/).
Возможно, вам это не нужно прямо сейчас, но может понадобиться позже. Установить [node.js](https://nodejs.org/en/).

После загрузки дважды щелкните и установите
После загрузки дважды щёлкните и установите

@ -113,7 +113,7 @@ v12.14.0
#### Установка Google Chrome
Установите [google chrome](https://www.google.com/chrome/), если у вас его еще нет. Мы можем написать небольшой код JavaScript в консоли браузера, но мы не используем консоль браузера для разработки приложений.
Установите [google chrome](https://www.google.com/chrome/), если у вас его ещё нет. Мы можем написать небольшой код JavaScript в консоли браузера, но мы не используем консоль браузера для разработки приложений.
После того, как вы откроете консоль Google Chrome, попробуйте изучить отмеченные кнопки. Мы будем проводить большую часть времени на консоли. Консоль - это место, куда идет ваш код JavaScript. Движок Google Console V8 изменяет ваш код JavaScript на машинный код.
После того, как вы откроете консоль Google Chrome, попробуйте изучить отмеченные кнопки. Мы будем проводить большую часть времени на консоли. Консоль - это место, куда идёт ваш код JavaScript. Движок Google Console V8 изменяет ваш код JavaScript на машинный код.
Давайте напишем код JavaScript на консоли Google Chrome:

Как вы можете видеть из приведенного выше фрагмента кода, `console.log()` может принимать несколько аргументов.
Как вы можете видеть из приведённого выше фрагмента кода, `console.log()` может принимать несколько аргументов.
Поздравляем! Вы написали свой первый код JavaScript, используя `console.log()`.
@ -246,11 +246,11 @@ VS Code - это очень популярный текстовый редакт

Если вы установили код VS Code, давайте начнем использовать его.
Если вы установили код VS Code, давайте начнём использовать его.
#### Как использовать VS Code
Откройте код VS Code, дважды щелкнув значок VS Code. Когда вы откроете его, вы получите такой интерфейс. Попробуйте взаимодействовать с помеченными значками.
Откройте код VS Code, дважды щёлкнув значок VS Code. Когда вы откроете его, вы получите такой интерфейс. Попробуйте взаимодействовать с помеченными значками.

@ -338,7 +338,7 @@ JavaScript можно добавить на веб-страницу тремя
### Внешний скрипт
Подобно внутреннему сценарию, ссылка на внешний сценарий может быть в `head` или `body`, но предпочтительно помещать ее в `body`.
Подобно внутреннему сценарию, ссылка на внешний сценарий может быть в `head` или `body`, но предпочтительно помещать её в `body`.
Во-первых, мы должны создать внешний файл JavaScript с расширением `.js`. Любой файл JavaScript заканчивается на `.js`. Создайте файл `introduction.js` внутри директории вашего проекта, напишите следующий код и подключите этот файл `.js` внизу `body`.
```js
@ -437,7 +437,7 @@ console.log("Hello, World!");
#### Пример
```js
true; // если свет включен, значение истинно
true; // если свет включён, значение истинно
false; // если свет выключен, значение False
```
@ -447,7 +447,7 @@ false; // если свет выключен, значение False
```js
let firstName;
console.log(firstName); // не определено, потому что оно еще не присвоено значению
console.log(firstName); // не определено, потому что оно ещё не присвоено значению
```
### Null
@ -460,7 +460,7 @@ let emptyValue = null;
## Проверка типов данных
Чтобы проверить тип данных определенного типа данных, мы используем оператор `typeof`. Смотрите следующий пример.
Чтобы проверить тип данных определённого типа данных, мы используем оператор `typeof`. Смотрите следующий пример.
Переменные являются _контейнером_ данных. Переменные, используются для хранения данных в ячейке памяти. Когда переменная объявлена, место в памяти зарезервировано. Когда переменной присваивается значение (данные), пространство памяти будет заполнено этими данными. Чтобы объявить переменную, мы используем ключевые слова `var`, `let` или `const`. Мы поговорим подробнее о`var`, `let` и `const` в других разделах (область действия). Пока приведенного выше объяснения достаточно.
Переменные являются _контейнером_ данных. Переменные, используются для хранения данных в ячейке памяти. Когда переменная объявлена, место в памяти зарезервировано. Когда переменной присваивается значение (данные), пространство памяти будет заполнено этими данными. Чтобы объявить переменную, мы используем ключевые слова `var`, `let` или `const`. Мы поговорим подробнее о`var`, `let` и `const` в других разделах (область действия). Пока приведённого выше объяснения достаточно.
Для переменной, которая изменяется в другое время, мы используем `let`. Если данные не меняются вообще, мы используем `const`. Например, PI, название страны, гравитация не меняются, и мы можем использовать `const`.
@ -598,12 +598,12 @@ Asabeneh teacher Finland

🌕 Ты великолепен. Вы только что выполнили задание первого дня, и вы на пути к величию. Теперь сделайте несколько упражнений для вашего мозга и ваших мышц.
🌕 Ты великолепен. ТЫ только что выполнил задание первого дня, и ты на пути к величию. Теперь сделай несколько упражнений для мозга и мышц.
# 💻 День 1: Упражнения
1. Написать однострочный комментарий, который говорит: _comments can make code readable_
2. Написать еще один комментарий, который говорит: _welcome to 30DaysOfJavaScript_
2. Написать ещё один комментарий, который говорит: _welcome to 30DaysOfJavaScript_
3. Написать многострочный комментарий, который говорит: _comments can make code readable, easy to use and informative_
4. Создать файл _variable.js_, объявить переменные и назначить строковые, логические, undefined и null типы данных.
5. Создайте файл _datatypes.js_ и используйте оператор JavaScript `typeof` для проверки различных типов данных. Проверьте тип данных каждой переменной
Yüksek dereceden (high order) fonksiyonlar, parametre olarak başka bir fonksiyonu içerisine alan veya bir başka fonksiyonu değer olarak döndürebilen fonksiyonlardır.
Bir fonksiyon parametre olarak geçilebiliyorsa bu fonksiyona ise **callback** fonksiyon denir.
### Callback
Callback fonksiyon yukarıda da söylediğimiz gibi bir başka fonksiyona parametre olarak verilen fonksiyonlardır.
```js
// callback fonksiyonun adını istediğimiz şekilde verebiliriz.
const callback = (n) => {
return n ** 2
}
// bir başka fonksiyonu callback olarak alan fonksiyon
function cube(callback, n) {
return callback(n) * n
}
console.log(cube(callback, 3))
```
### Returning function
Yüksek dereceden fonksiyonlar bir fonksiyonu değer olarak geri döndürebilir.
```js
// Bir fonksiyonun başka bir fonksiyonu geri döndürme örneği.
const higherOrder = n => {
const doSomething = m => {
const doWhatEver = t => {
return 2 * n + 3 * m + t
}
return doWhatEver
}
return doSomething
}
console.log(higherOrder(2)(3)(10))
```
Callback fonksiyonunu nasıl kullandığımızı görelim. Örneğin _foreach_ metodu callback kullanan metotlarından biridir.
```js
const numbers = [1, 2, 3, 4, 5]
const sumArray = arr => {
let sum = 0
const callback = function(element) {
sum += element
}
arr.forEach(callback)
return sum
}
console.log(sumArray(numbers))
```
```sh
15
```
Yukarıdaki örnek aşağıdaki gibi basitleştirilebilir::
```js
const numbers = [1, 2, 3, 4]
const sumArray = arr => {
let sum = 0
arr.forEach(function(element) {
sum += element
})
return sum
}
console.log(sumArray(numbers))
```
```sh
15
```
### Setting time
JavaScript'te bazı fonksiyonları belirli bir zaman aralığında yürütebiliriz veya bazı fonksiyonları yürütmek için belirli bir süre planlama (bekleme) yapabiliriz.
- setInterval
- setTimeout
#### **setInterval** fonksiyonu ile süre ayarlama
JavaScript'te, belirli bir zaman aralığında sürekli olarak istediğimiz şeyi yapmak için **SetInterval** fonksiyonunu kullanırız. SetInterval, genel olarak bir callback fonksiyonu ve ikinci olarak, belirlemek istediğimiz süreyi parametre alararak kullanılır.
In JavaScript, we use setTimeout higher order function to execute some action at some time in the future. The setTimeout global method take a callback function and a duration as a parameter. The duration is in milliseconds and the callback wait for that amount of time.
Javascript'te ileriye dönük çalışacak fonksiyonlar planlayabiliriz. Tam da bu iş için **setTimeOut** metodu imdadımıza koşuyor. setTimeOut fonksiyonu da setInterval fonksiyonuna benzer şekilde bir callback fonksiyon ve ms cinsinden bir süre değerini parametre olarak alır.
```js
// syntax
function callback() {
// code goes here
}
setTimeout(callback, duration)
```
```js
function sayHello() {
console.log('Hello')
}
setTimeout(sayHello, 2000) //2 saniye bekledikten sonra "Hello" yazdıracak
JavaScript'in en son sürümü, normal döngü yazmak yerine karmaşık sorunları çözmemize yardımcı olabilecek birçok yerleşik yöntem sunmuştur.Göreceğimiz tüm metotlar callback fonksiyonu ile birlikte kullanılabilir. Bu bölümde, _forEach_, _map_, _filter_, _reduce_, _find_, _every_, _some_, and _sort_ metodlarını göreceğiz
### forEach
_forEach_: Bir dizi elemanlarını sırasıyla gezer. "element", "index" ve dizinin kendisi ile callback fonksiyonunu parametre olarak alabilir. "index" ve dizinin kendisi isteğe bağlı olarak parametre olarak verilmeyebilir.
```js
arr.forEach(function (element, index, arr) {
console.log(index, element, arr)
})
// Yukarıdaki kod arrow function kullanılarak yazılabilir.
_map_:Bir dizi elemanını yinelemek ve dizi öğelerini değiştirmek. callback fonksiyonla birlikte "elements", "index" yeni bir diziyi parametre olarak alabilir.
const areAllStr = names.some((name) => typeof name === 'number') // Are all strings ?
console.log(areAllStr) // false
```
### sort
_sort_: sort fonksiyonu, bir diziyi, öğelerini dizelere dönüştürerek ve bu dizeleri Unicode kod karakterleri sırasına göre karşılaştırarak (diziyi alfabetik olarak sıralar) sıralamanıza olanak tanır. Yeni bir dizi oluşturmadan eldeki olan diziyi düzenler
Sayısal değerleri artan veya azalan düzende sıralamak için, sıralama kriterini belirleyen bir fonksiyon kullanmamız gerekir. Sıralama yöntemi neyse ki negatif, sıfır ve pozitif değerleri doğru sırada sıralayabilir. **Sort()** methodu iki değeri karşılaştırdığında, değerleri karşılaştırma fonksiyonuna gönderir ve döndürülen değere göre sıralar.
- Sonuç negatifse; a, b'den önce sıralanır
- Sonuç pozitifse; a, b'den sonra sıralanır
- Sonuç 0 ise; hiçbir şey değişmez
Tek ihtiyacımız olan ise sort() metodu içinde karşılaştırma fonksiyonu kullanmak.
```js
numbers.sort(function (a, b) {
return a - b
})
console.log(numbers) // [3.14, 9.81, 37, 100]
numbers.sort(function (a, b) {
return b - a
})
console.log(numbers) //[100, 37, 9.81, 3.14]
```
#### Array nesnelerini sıralamak
Bir dizideki nesneleri sıraladığımız zaman karşılaştırmak için key objesini kullanırız. Aşağıdaki örneğe bakalım.
```js
objArr.sort(function (a, b) {
if (a.key <b.key)return-1
if (a.key > b.key) return 1
return 0
})
// or
objArr.sort(function (a, b) {
if (a['key'] <b['key'])return-1
if (a['key'] > b['key']) return 1
return 0
})
const users = [
{ name: 'Asabeneh', age: 150 },
{ name: 'Brook', age: 50 },
{ name: 'Eyob', age: 100 },
{ name: 'Elias', age: 22 },
]
users.sort((a, b) => {
if (a.age <b.age)return-1
if (a.age > b.age) return 1
return 0
})
console.log(users) // sorted ascending
// [{…}, {…}, {…}, {…}]
```
🌕 Çok iyi gidiyorsunuz. Asla vazgeçmeyin, çünkü harika şeyler zaman alır. 9. Günü tamamladın ve mükemmelliğe giden yolda 9 adım attınız. Şimdi beyniniz ve kasınız için egzersiz yapın.
## 💻 Exercises
### Exercises: Level 1
```js
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
1. Aralarındaki farkı açıklayın: **_forEach, map, filter, and 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.
6. Use **_map_** to create a new array by changing each country to uppercase in the countries array.
7. Use **_map_** to create an array of countries length from countries array.
8. Use **_map_** to create a new array by changing each number to square in the numbers array
9. Use **_map_** to change to each name to uppercase in the names array
10. Use **_map_** to map the products array to its corresponding prices.
11. Use **_filter_** to filter out countries containing **_land_**.
12. Use **_filter_** to filter out countries having six character.
13. Use **_filter_** to filter out countries containing six letters and more in the country array.
14. Use **_filter_** to filter out country start with 'E';
15. Use **_filter_** to filter out only prices with values.
16. Declare a function called getStringLists which takes an array as a parameter and then returns an array only with string items.
17. Use **_reduce_** to sum all the numbers in the numbers array.
18. Use **_reduce_** to concatenate all the countries and to produce this sentence: **_Estonia, Finland, Sweden, Denmark, Norway, and IceLand are north European countries_**
19. Explain the difference between **_some_** and **_every_**
20. Use **_some_** to check if some names' length greater than seven in names array
21. Use **_every_** to check if all the countries contain the word land
22. Explain the difference between **_find_** and **_findIndex_**.
23. Use **_find_** to find the first country containing only six letters in the countries array
24. Use **_findIndex_** to find the position of the first country containing only six letters in the countries array
25. Use **_findIndex_** to find the position of **_Norway_** if it doesn't exist in the array you will get -1.
26. Use **_findIndex_** to find the position of **_Russia_** if it doesn't exist in the array you will get -1.
### Exercises: Level 2
1. Find the total price of products by chaining two or more array iterators(eg. arr.map(callback).filter(callback).reduce(callback))
1. Find the sum of price of products using only reduce reduce(callback))
1. Declare a function called **_categorizeCountries_** which returns an array of countries which have some common pattern(you find the countries array in this repository as countries.js(eg 'land', 'ia', 'island','stan')).
1. Create a function which return an array of objects, which is the letter and the number of times the letter use to start with a name of a country.
1. Declare a **_getFirstTenCountries_** function and return an array of ten countries. Use different functional programming to work on the countries.js array
1. Declare a **_getLastTenCountries_** function which which returns the last ten countries in the countries array.
1. Find out which _letter_ is used many _times_ as initial for a country name from the countries array (eg. Finland, Fiji, France etc)
### Exercises: Level 3
1. Use the countries information, in the data folder. Sort countries by name, by capital, by population
1. \*\*\* Find the 10 most spoken languages:
````js
// Your output should look like this
console.log(mostSpokenLanguages(countries, 10))
[
{country: 'English',count:91},
{country: 'French',count:45},
{country: 'Arabic',count:25},
{country: 'Spanish',count:24},
{country:'Russian',count:9},
{country:'Portuguese', count:9},
{country:'Dutch',count:8},
{country:'German',count:7},
{country:'Chinese',count:5},
{country:'Swahili',count:4}
]
// Your output should look like this
console.log(mostSpokenLanguages(countries, 3))
[
{country: 'English',count: 91},
{country: 'French',count: 45},
{country: 'Arabic',count: 25},
]```
````
2. \*\*\* Use countries_data.js file create a function which create the ten most populated countries
{country: 'United States of America', population: 323947000}
]
```
````
3. \*\*\* Try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create an object called statistics and create all the functions which do statistical calculations as method for the statistics object. Check the output below.
[ Day 9](..09_Day_Higher_order_functions09_day_higher_order_functions.md) [>> Day 11 ](..11_Day_Destructuring_and_spreading11_day_destructuring_and_spreading.md)
counts.push({ lang l, count filteredLang.length })
}
console.log(counts)
```
```js
[
{ lang 'English', count 3 },
{ lang 'Finnish', count 1 },
{ lang 'French', count 2 },
{ lang 'Spanish', count 1 },
]
```
Set'in farklı bir kullanımı. Örneğin dizideki benzersiz öğeyi saymak için.
```js
const numbers = [5, 3, 2, 5, 5, 9, 4, 5]
const setOfNumbers = new Set(numbers)
console.log(setOfNumbers)
```
```sh
Set(5) {5, 3, 2, 9, 4}
```
### Set'lerin birleşimi
iki set nesnesini birleştirmek yayılma operatörü kullanılarak elde edilebilir A ve B set'lerinin birleşimini (A U B) bulmak için aşağıdaki kodlara göz atın
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let c = [...a, ...b]
let A = new Set(a)
let B = new Set(b)
let C = new Set(c)
console.log(C)
```
```sh
Set(6) {1, 2, 3, 4, 5,6}
```
### Set'lerin kesişimi
iki set nesnesinin kesişimini bulmak için filter methodu kullanılması gerekir. A ve B setlerinin kesişimi (A ∩ B) bulmak için aşağıdaki kodlara göz atın
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let A = new Set(a)
let B = new Set(b)
let c = a.filter((num) = B.has(num))
let C = new Set(c)
console.log(C)
```
```sh
Set(3) {3, 4, 5}
```
### Set'lerin farkı
iki set nesnesinin farkını bulmak için filter methodu kullanılması gerekir. A ve B setlerinin farkını (A B) bulmak için aşağıdaki kodlara göz atın
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let A = new Set(a)
let B = new Set(b)
let c = a.filter((num) = !B.has(num))
let C = new Set(c)
console.log(C)
```
```sh
Set(2) {1, 2}
```
## Map
### Boş map oluşturma
```js
const map = new Map()
console.log(map)
```
```sh
Map(0) {}
```
### Bir diziden map oluşturma
```js
countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo'],
]
const map = new Map(countries)
console.log(map)
console.log(map.size)
```
```sh
Map(3) {Finland = Helsinki, Sweden = Stockholm, Norway = Oslo}
3
```
### Map'e değerler ekleme
```js
const countriesMap = new Map()
console.log(countriesMap.size) 0
countriesMap.set('Finland', 'Helsinki')
countriesMap.set('Sweden', 'Stockholm')
countriesMap.set('Norway', 'Oslo')
console.log(countriesMap)
console.log(countriesMap.size)
```
```sh
Map(3) {Finland = Helsinki, Sweden = Stockholm, Norway = Oslo}
3
```
### Map'ten değer alma
```js
console.log(countriesMap.get('Finland'))
```
```sh
Helsinki
```
### Map içindeki anahtarı kontrol etme
Eğer Map içinde bir anahtarın olup olmadığını kontrol etmek istiyorsak has methodunu kullanabiliriz bu method bize true veya false döndürür.
```js
console.log(countriesMap.has('Finland'))
```
```sh
true
```
Map içindeki bütün değerleri döngü kullanarak almak
```js
for (const country of countriesMap) {
console.log(country)
}
```
```sh
(2) [Finland, Helsinki]
(2) [Sweden, Stockholm]
(2) [Norway, Oslo]
```
```js
for (const [country, city] of countriesMap){
console.log(country, city)
}
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
```
🌕 Büyük bir ilerleme kateddiniz, durdurulamazsınız. Devam edin! 10.gün zorluklarını yeni tamamladınız ve mükemmeliğe giden yolda 10 adım öndesiniz. Şimdi beyniniz ve kaslarınız için bazı egzersizler yapın.
## Egzersiz
### Egzersiz:Seviye 1
```js
const a = [4, 5, 8, 9]
const b = [3, 4, 5, 7]
const countries = ['Finland', 'Sweden', 'Norway']
```
1.Boş bir set oluşturun
2.Döngü kullanarak 0 ile 10 aralığını içeren bir set oluşturun
3.Set içinden bir eleman silin
4.Set'i temizleyin
5.5 string eleman içeren bir set oluşturun (dizi ile oluşturulacak)
6. bir ülke map'ı oluşturun ve içindeki ülkelerin karakter sayısını girin
### Egzersiz:Seviye 2
1.A birleşim B'yi bulun
2.A kesişim B'yi bulun
3. A ile B'yi bul
### Egzersiz:Seviye 3
1.Ülkeler nesne dosyasında kaç tane dil var
1. En çok konuşulan 10 dili bulmak için ülke verilerini kullanın
```js
Çıktınız böyle görünmelidir
console.log(mostSpokenLanguages(countries, 10))
[
{ English 91 },
{ French 45 },
{ Arabic 25 },
{ Spanish 24 },
{ Russian 9 },
{ Portuguese 9 },
{ Dutch 8 },
{ German 7 },
{ Chinese 5 },
{ Swahili 4 },
{ Serbian 4 }
]
Çıktınız böyle görünmelidir
console.log(mostSpokenLanguages(countries, 3))
[
{English91},
{French45},
{Arabic25}
]
```
🎉 TEBRİKLER ! 🎉
[ Day 9](..09_Day_Higher_order_functions09_day_higher_order_functions.md) [ >> Day 11](..11_Day_Destructuring_and_spreading11_day_destructuring_and_spreading.md)
Dizideki tüm elemanlara değişken atanmayabilir. İlkinin birkaçını yok edip ve kalanını spread operatörünü (...) kullanarak dizi olarak alabiliriz.
```js
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [num1, num2, num3, ...rest] = nums
console.log(num1, num2, num3)
console.log(rest)
```
```sh
1 2 3
[4, 5, 6, 7, 8, 9, 10]
```
### Iterasyon sırasında Destructuring
```js
const countries = [['Finland', 'Helsinki'], ['Sweden', 'Stockholm'], ['Norway', 'Oslo']]
for (const [country, city] of countries) {
console.log(country, city)
}
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
```
```js
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]
for(const [first, second, third] of fullStack) {
console.log(first, second, third)
}
```
```sh
HTML CSS JS
Node Express MongoDB
```
### Objeye Destructuring işlemi yapma
Destruct işleminde kullandığımız değişkenin adı, nesnenin anahtarı veya özelliği ile tamamen aynı olmalıdır. Aşağıdaki örneğe bakınız.
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width, height, area, perimeter } = rectangle
console.log(width, height, area, perimeter)
```
```sh
20 10 200 undefined
```
### Yapılandırma sırasında yeniden adlandırma
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width: w, height: h, area: a, perimeter: p } = rectangle
console.log(w, h, a, p)
```
```sh
20 10 200 undefined
```
Eğer anahtar nesnede bulunmazsa, değişken tanımsız olarak atanır. Anahtar nesnede olmadığında bildirim sırasında varsayılan bir değer verilebilir. Aşağıdaki örneğe bakınız.
Anahtarları bir fonksiyon parametresi olarak destructuring işlemi uygulama. Bir dikdörtgen nesnesi alan ve bir dikdörtgenin çevresini döndüren bir fonksiyon oluşturalım.
personInfo = `${firstName} ${lastName} lives in ${country}. He is ${age} years old. He is an ${job}. He teaches ${formattedSkills} and ${
skills[skills.length - 1]
}. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo
}
console.log(getPersonInfo(person))
/*
Asabeneh Yetayeh lives in Finland. He is 250 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)
*/
```
### Iterasyon sırasında objeye destructuring işlemi uygulamak
```js
const todoList = [
{
task:'Prepare JS Test',
time:'4/1/2020 8:30',
completed:true
},
{
task:'Give JS Test',
time:'4/1/2020 10:00',
completed:false
},
{
task:'Assess Test Result',
time:'4/1/2020 1:00',
completed:false
}
]
for (const {task, time, completed} of todoList){
console.log(task, time, completed)
}
```
```sh
Prepare JS Test 4/1/2020 8:30 true
Give JS Test 4/1/2020 10:00 false
Assess Test Result 4/1/2020 1:00 false
```
### Spread veya Rest Operatörleri
Bir diziye destructuring işlemi uygulandığında, kalan elemanları dizi olarak almak için yayılma operatörünü (...) kullanırız.Buna ek olarak, dizi öğelerini başka bir diziye yaymak için spread operatörünü kullanırız.
### Dizi ogelerinin geri kalanını almak için spread operatörü
Sınırsız sayıda argüman alan bir ok fonksiyonu yazmak istersek, bir yayılma spread kullanırız. Parametre olarak bir spread işleci kullanırsak, bir işlevi çağırdığımızda iletilen bağımsız değişken bir diziye dönüşecektir.
```js
const sumAllNums = (...args) => {
console.log(args)
}
sumAllNums(1, 2, 3, 4, 5)
```
```sh
[1, 2, 3, 4, 5]
```
```js
const sumAllNums = (...args) => {
let sum = 0
for (const num of args){
sum += num
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4, 5))
```
```sh
15
```
🌕 Büyük bir ilerleme kateddiniz, durdurulamazsınız. Devam edin! 11.gün zorluklarını yeni tamamladınız ve mükemmeliğe giden yolda 10 adım öndesiniz. Şimdi beyniniz ve kaslarınız için bazı egzersizler yapın.
## Egzersiz
### Egzersiz: Seviye 1
```js
const constants = [2.72, 3.14, 9.81, 37, 100]
const countries = ['Finland', 'Estonia', 'Sweden', 'Denmark', 'Norway']
const rectangle = {
width: 20,
height: 10,
area: 200,
perimeter: 60
}
const users = [
{
name:'Brook',
scores:75,
skills:['HTM', 'CSS', 'JS'],
age:16
},
{
name:'Alex',
scores:80,
skills:['HTM', 'CSS', 'JS'],
age:18
},
{
name:'David',
scores:75,
skills:['HTM', 'CSS'],
age:22
},
{
name:'John',
scores:85,
skills:['HTML'],
age:25
},
{
name:'Sara',
scores:95,
skills:['HTM', 'CSS', 'JS'],
age: 26
},
{
name:'Martha',
scores:80,
skills:['HTM', 'CSS', 'JS'],
age:18
},
{
name:'Thomas',
scores:90,
skills:['HTM', 'CSS', 'JS'],
age:20
}
]
```
1. E, pi, yerçekimi, humanBodyTemp, waterBoilingTemp sabitleri dizisinin öğelerini destructuring işlemi uygulayın ve atayın.
2. fin, est, sw, den veya nor olarak ülkeler dizisinin öğelerini destructuring işlemi uygulayın ve atayın.
3. Dikdörtgen nesnesini özelliklerine veya anahtarlarına göre destructuring işlemi uygulayın.
### Egzersiz: Seviye 2
1. Kullanıcılar dizisini Iterator ve destructuring kullanarak nesnenin tüm anahtarlarını alın.
2. İkiden az beceriye sahip kişileri bulun.
### Egzersiz: Seviye 3
1. Tüm ülkelerin adını, sermayesini, nüfusunu ve dillerini yazdıran ülkeler nesnesine destructuring işlemi uygulayın
2. Küçük bir geliştirici, öğrenci adını, becerilerini ve puanını okunması kolay olmayabilecek diziler halinde yapılandırır.Aşağıdaki dizi adını ada, beceriler dizisini becerilere, puan dizisini puanlara, JavaScript puanını jsScore'a ve React puanını React değişkenine tek bir satırda destructuring işlemi uygulayın.