Merge pull request #664 from Dikendev/master

Portuguese Day 2 Translation
pull/699/merge
Asabeneh 2 years ago committed by GitHub
commit 2938cc3839
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,979 +0,0 @@
<div align="center">
<h1> 30 Days Of JavaScript: Tipos de Dados</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Janeiro, 2020</small>
</sub>
</div>
</div>
[<< Dia 1](../readMe.md) | [Dia 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)
![Thirty Days Of JavaScript](/images/banners/day_1_2.png)
- [📔 Dia 2](#-dia-2)
- [Tipo de Dados](#tipos-de-dados)
- [Tipos de Dados Primitivos](#tipos-de-dados-primitivos)
- [Tipos de Dados Não Primitivos](#tipos-de-dados-não-primitivos)
- [Números](#Números)
- [Declarando Tipos de Dados Numéricos](#declarando-tipos-de-dados-numéricos)
- [Math Objeto](#math-objeto)
- [Gerador de Número Aleatório](#random-number-generator)
- [Strings](#strings)
- [String Concatenação](#string-concatenation)
- [Concatenando Usando o Operador de Adição](#concatenating-using-addition-operator)
- [Long Literal Strings ](#long-literal-strings)
- [Escape Sequences in Strings](#escape-sequences-in-strings)
- [Template Literals (Template Strings)](#template-literals-template-strings)
- [String Methods](#string-methods)
- [Checking Data Types and Casting](#checking-data-types-and-casting)
- [Checking Data Types](#checking-data-types)
- [Changing Data Type (Casting)](#changing-data-type-casting)
- [String to Int](#string-to-int)
- [String to Float](#string-to-float)
- [Float to Int](#float-to-int)
- [💻 Day 2: Exercises](#-day-2-exercises)
- [Exercise: Level 1](#exercise-level-1)
- [Exercise: Level 2](#exercise-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 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
console.log(age, gravity, mass, PI, boilingPoint, bodyTemp)
```
### Math Objeto
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.
![Accessing sting by index](../images/string_indexes.png)
Let us access different characters in 'JavaScript' string.
```js
let string = 'JavaScript'
let firstLetter = string[0]
console.log(firstLetter) // J
let secondLetter = string[1] // a
let thirdLetter = string[2]
let lastLetter = string[9]
console.log(lastLetter) // t
let lastIndex = string.length - 1
console.log(lastIndex) // 9
console.log(string[lastIndex]) // t
```
3. *toUpperCase()*: this method changes the string to uppercase letters.
```js
let string = 'JavaScript'
console.log(string.toUpperCase()) // JAVASCRIPT
let firstName = 'Asabeneh'
console.log(firstName.toUpperCase()) // ASABENEH
let country = 'Finland'
console.log(country.toUpperCase()) // FINLAND
```
4. *toLowerCase()*: this method changes the string to lowercase letters.
```js
let string = 'JavasCript'
console.log(string.toLowerCase()) // javascript
let firstName = 'Asabeneh'
console.log(firstName.toLowerCase()) // asabeneh
let country = 'Finland'
console.log(country.toLowerCase()) // finland
```
5. *substr()*: It takes two arguments, the starting index and number of characters to slice.
```js
let string = 'JavaScript'
console.log(string.substr(4,6)) // Script
let country = 'Finland'
console.log(country.substr(3, 4)) // land
```
6. *substring()*: It takes two arguments, the starting index and the stopping index but it doesn't include the character at the stopping index.
```js
let string = 'JavaScript'
console.log(string.substring(0,4)) // Java
console.log(string.substring(4,10)) // Script
console.log(string.substring(4)) // Script
let country = 'Finland'
console.log(country.substring(0, 3)) // Fin
console.log(country.substring(3, 7)) // land
console.log(country.substring(3)) // land
```
7. *split()*: The split method splits a string at a specified place.
```js
let string = '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"]
console.log(countries.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
```
8. *trim()*: Removes trailing space in the beginning or the end of a string.
```js
let string = ' 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
let country = 'Finland'
console.log(country.replace('Fin', 'Noman')) // Nomanland
```
11. *charAt()*: Takes index and it returns the value at that index
```js
string.charAt(index)
```
```js
let string = '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.'
console.log(string.lastIndexOf('love')) // 67
console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38
```
15. *concat()*: it takes many substrings and joins them.
```js
string.concat(substring, substring, substring)
```
```js
let string = '30'
console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript
let country = 'Fin'
console.log(country.concat("land")) // Finland
```
16. *startsWith*: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
```js
//syntax
string.startsWith(substring)
```
```js
let string = 'Love is the best to in this world'
console.log(string.startsWith('Love')) // true
console.log(string.startsWith('love')) // false
console.log(string.startsWith('world')) // false
let country = 'Finland'
console.log(country.startsWith('Fin')) // true
console.log(country.startsWith('fin')) // false
console.log(country.startsWith('land')) // false
```
17. *endsWith*: it takes a substring as an argument and it checks if the string ends with that specified substring. It returns a boolean(true or false).
```js
string.endsWith(substring)
```
```js
let string = 'Love is the most powerful feeling in the world'
console.log(string.endsWith('world')) // true
console.log(string.endsWith('love')) // false
console.log(string.endsWith('in the world')) // true
let country = 'Finland'
console.log(country.endsWith('land')) // true
console.log(country.endsWith('fin')) // false
console.log(country.endsWith('Fin')) // false
```
18. *search*: it takes a substring as an argument and it returns the index of the first match. The search value can be a string or a regular expression pattern.
```js
string.search(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2
console.log(string.search(/javascript/gi)) // 7
```
19. *match*: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign.
```js
let string = 'love'
let patternOne = /love/ // with out any flag
let patternTwo = /love/gi // g-means to search in the whole text, i - case insensitive
```
Match syntax
```js
// syntax
string.match(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.match('love'))
```
```sh
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
```
```js
let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
```
Let us extract numbers from text using a regular expression. This is not the regular expression section, do not panic! We will cover regular expressions later on.
```js
let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge'
let regEx = /\d+/
// d with escape character means d not a normal d instead acts a digit
// + means one or more digit numbers,
// if there is g after that it means global, search everywhere.
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
```
20. *repeat()*: it takes a number as argument and it returns the repeated version of the string.
```js
string.repeat(n)
```
```js
let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
```
## Checking Data Types and Casting
### Checking Data Types
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)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

@ -1,34 +0,0 @@
const PI = Math.PI
console.log(PI) // 3.141592653589793
console.log(Math.round(PI)) // 3; to round values to the nearest number
console.log(Math.round(9.81)) // 10
console.log(Math.floor(PI)) // 3; rounding down
console.log(Math.ceil(PI)) // 4; rounding up
console.log(Math.min(-5, 3, 20, 4, 5, 10)) // -5, returns the minimum value
console.log(Math.max(-5, 3, 20, 4, 5, 10)) // 20, returns the maximum value
const randNum = Math.random() // creates random number between 0 to 0.999999
console.log(randNum)
// Let create random number between 0 to 10
const num = Math.floor(Math.random() * 11) // creates random number between 0 and 10
console.log(num)
//Absolute value
console.log(Math.abs(-10)) //10
//Square root
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) //1.4142135623730951
// Power
console.log(Math.pow(3, 2)) // 9
console.log(Math.E) // 2.718
// Logarithm
//Returns the natural logarithm of base E of x, Math.log(x)
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
// Trigonometry
console.log(Math.sin(0))
console.log(Math.sin(60))
console.log(Math.cos(0))
console.log(Math.cos(60))

@ -1,30 +0,0 @@
let nums = [1, 2, 3]
nums[0] = 10
console.log(nums) // [10, 2, 3]
let nums = [1, 2, 3]
let numbers = [1, 2, 3]
console.log(nums == numbers) // false
let userOne = {
name: 'Asabeneh',
role: 'teaching',
country: 'Finland'
}
let userTwo = {
name: 'Asabeneh',
role: 'teaching',
country: 'Finland'
}
console.log(userOne == userTwo) // false
let numbers = nums
console.log(nums == numbers) // true
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
let userTwo = userOne
console.log(userOne == userTwo) // true

@ -1,9 +0,0 @@
let age = 35
const gravity = 9.81 //we use const for non-changing values, gravitational constant in m/s2
let mass = 72 // mass in Kilogram
const PI = 3.14 // pi a geometrical constant
//More Examples
const boilingPoint = 100 // temperature in oC, boiling point of water which is a constant
const bodyTemp = 37 // oC average human body temperature, which is a constant
console.log(age, gravity, mass, PI, boilingPoint, bodyTemp)

@ -1,14 +0,0 @@
let word = 'JavaScript'
// we dont' modify string
// we don't do like this, word[0] = 'Y'
let numOne = 3
let numTwo = 3
console.log(numOne == numTwo) // true
let js = 'JavaScript'
let py = 'Python'
console.log(js == py) //false
let lightOn = true
let lightOff = false
console.log(lightOn == lightOff) // false

@ -1,19 +0,0 @@
// Declaring different variables of different data types
let space = ' '
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
// Concatenating using addition operator
let fullName = firstName + space + lastName // concatenation, merging two string together.
console.log(fullName)
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country // ES5
console.log(personInfoOne)
// Concatenation: Template Literals(Template Strings)
let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.` //ES6 - String interpolation method
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`
console.log(personInfoTwo)
console.log(personInfoThree)

@ -1,7 +0,0 @@
let space = ' ' // an empty space string
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'

@ -1,12 +0,0 @@
// Let us access the first character in 'JavaScript' string.
let string = 'JavaScript'
let firstLetter = string[0]
console.log(firstLetter) // J
let secondLetter = string[1] // a
let thirdLetter = string[2]
let lastLetter = string[9]
console.log(lastLetter) // t
let lastIndex = string.length - 1
console.log(lastIndex) // 9
console.log(string[lastIndex]) // t

@ -1,6 +0,0 @@
// charAt(): Takes index and it returns the value at that index
string.charAt(index)
let string = '30 Days Of JavaScript'
console.log(string.charAt(0)) // 3
let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)) // t

@ -1,7 +0,0 @@
// charCodeAt(): Takes index and it returns char code(ASCII number) of the value at that index
string.charCodeAt(index)
let string = '30 Days Of JavaScript'
console.log(string.charCodeAt(3)) // D ASCII number is 51
let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)) // t ASCII is 116

@ -1,6 +0,0 @@
// concat(): it takes many substrings and creates concatenation.
// string.concat(substring, substring, substring)
let string = '30'
console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript
let country = 'Fin'
console.log(country.concat("land")) // Finland

@ -1,11 +0,0 @@
// endsWith: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
// string.endsWith(substring)
let string = 'Love is the best to in this world'
console.log(string.endsWith('world')) // true
console.log(string.endsWith('love')) // false
console.log(string.endsWith('in this world')) // true
let country = 'Finland'
console.log(country.endsWith('land')) // true
console.log(country.endsWith('fin')) // false
console.log(country.endsWith('Fin')) // false

@ -1,14 +0,0 @@
// includes(): It takes a substring argument and it check if substring argument exists in the string. includes() returns a boolean. It checks if a substring exist in a string and it returns true if it exists and false if it doesn't exist.
let string = '30 Days Of JavaScript'
console.log(string.includes('Days')) // true
console.log(string.includes('days')) // false
console.log(string.includes('Script')) // true
console.log(string.includes('script')) // false
console.log(string.includes('java')) // false
console.log(string.includes('Java')) // true
let country = 'Finland'
console.log(country.includes('fin')) // false
console.log(country.includes('Fin')) // true
console.log(country.includes('land')) // true
console.log(country.includes('Land')) // false

@ -1,11 +0,0 @@
// indexOf(): Takes takes a substring and if the substring exists in a string it returns the first position of the substring if does not exist it returns -1
string.indexOf(substring)
let string = '30 Days Of JavaScript'
console.log(string.indexOf('D')) // 3
console.log(string.indexOf('Days')) // 3
console.log(string.indexOf('days')) // -1
console.log(string.indexOf('a')) // 4
console.log(string.indexOf('JavaScript')) // 11
console.log(string.indexOf('Script')) //15
console.log(string.indexOf('script')) // -1

@ -1,6 +0,0 @@
// lastIndexOf(): Takes takes a substring and if the substring exists in a string it returns the last position of the substring if it does not exist it returns -1
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.lastIndexOf('love')) // 67
console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38

@ -1,6 +0,0 @@
// length: The string length method returns the number of characters in a string included empty space. Example:
let js = 'JavaScript'
console.log(js.length) // 10
let firstName = 'Asabeneh'
console.log(firstName.length) // 8

@ -1,22 +0,0 @@
// match: it takes a substring or regular expression pattern as an argument and it returns an array if there is match if not it returns null. Let us see how a regular expression pattern looks like. It starts with / sign and ends with / sign.
let string = 'love'
let patternOne = /love/ // with out any flag
let patternTwo = /love/gi // g-means to search in the whole text, i - case insensitive
string.match(substring)
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.match('love')) //
/*
output
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
*/
let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
// Let us extract numbers from text using regular expression. This is not regular expression section, no panic.
let txt = 'In 2019, I run 30 Days of Python. Now, in 2020 I super exited to start this challenge'
let regEx = /\d/g // d with escape character means d not a normal d instead acts a digit
// + means one or more digit numbers,
// if there is g after that it means global, search everywhere.
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]

@ -1,4 +0,0 @@
// repeat(): it takes a number argument and it returned the repeated version of the string.
// string.repeat(n)
let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove

@ -1,7 +0,0 @@
// replace(): takes to parameter the old substring and new substring.
// string.replace(oldsubstring, newsubstring)
let string = '30 Days Of JavaScript'
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
let country = 'Finland'
console.log(country.replace('Fin', 'Noman')) // Nomanland

@ -1,4 +0,0 @@
// search: it takes a substring as an argument and it returns the index of the first match.
// string.search(substring)
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2

@ -1,10 +0,0 @@
// split(): The split method splits a string at a specified place.
let string = '30 Days Of JavaScript'
console.log(string.split()) // ["30 Days Of JavaScript"]
console.log(string.split(' ')) // ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh'
console.log(firstName.split()) // ["Asabeneh"]
console.log(firstName.split('')) // ["A", "s", "a", "b", "e", "n", "e", "h"]
let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(countries.split(',')) // ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(', ')) // ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]

@ -1,11 +0,0 @@
// startsWith: it takes a substring as an argument and it checks if the string starts with that specified substring. It returns a boolean(true or false).
// string.startsWith(substring)
let string = 'Love is the best to in this world'
console.log(string.startsWith('Love')) // true
console.log(string.startsWith('love')) // false
console.log(string.startsWith('world')) // false
let country = 'Finland'
console.log(country.startsWith('Fin')) // true
console.log(country.startsWith('fin')) // false
console.log(country.startsWith('land')) // false

@ -1,5 +0,0 @@
//substr(): It takes two arguments,the starting index and number of characters to slice.
let string = 'JavaScript'
console.log(string.substr(4,6)) // Script
let country = 'Finland'
console.log(country.substr(3, 4)) // land

@ -1,9 +0,0 @@
// substring(): It takes two arguments,the starting index and the stopping index but it doesn't include the stopping index.
let string = 'JavaScript'
console.log(string.substring(0,4)) // Java
console.log(string.substring(4,10)) // Script
console.log(string.substring(4)) // Script
let country = 'Finland'
console.log(country.substring(0, 3)) // Fin
console.log(country.substring(3, 7)) // land
console.log(country.substring(3)) // land

@ -1,7 +0,0 @@
// toLowerCase(): this method changes the string to lowercase letters.
let string = 'JavasCript'
console.log(string.toLowerCase()) // javascript
let firstName = 'Asabeneh'
console.log(firstName.toLowerCase()) // asabeneh
let country = 'Finland'
console.log(country.toLowerCase()) // finland

@ -1,8 +0,0 @@
// toUpperCase(): this method changes the string to uppercase letters.
let string = 'JavaScript'
console.log(string.toUpperCase()) // JAVASCRIPT
let firstName = 'Asabeneh'
console.log(firstName.toUpperCase()) // ASABENEH
let country = 'Finland'
console.log(country.toUpperCase()) // FINLAND

@ -1,7 +0,0 @@
//trim(): Removes trailing space in the beginning or the end of a string.
let string = ' 30 Days Of JavaScript '
console.log(string) //
console.log(string.trim(' ')) //
let firstName = ' Asabeneh '
console.log(firstName)
console.log(firstName.trim()) //

@ -0,0 +1,972 @@
<div align="center">
<h1> 30 Dias De JavaScript: Tipos de Dados</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Janeiro, 2020</small>
</sub>
</div>
</div>
[<< Dia 1](../readMe.md) | [Dia 3 >>](../Dia_03_Booleanos_Operadores_Data/dia_03_booleanos_operadores_data.md)
![Thirty Days Of JavaScript](/images/banners/day_1_2.png)
- [📔 Dia 2](#-dia-2)
- [Tipo de Dados](#tipos-de-dados)
- [Tipos de Dados Primitivos](#tipos-de-dados-primitivos)
- [Tipos de Dados Não Primitivos](#tipos-de-dados-não-primitivos)
- [Números](#Números)
- [Declarando Tipos de Dados Numéricos](#declarando-tipos-de-dados-numéricos)
- [Objeto Math](#objeto-math)
- [Gerador de Número Aleatório](#gerador-de-número-aleatório)
- [Strings](#strings)
- [String Concatenação](#string-concatenação)
- [Concatenando Usando o Operador de Adição](#concatenando-usando-o-operador-de-adição)
- [Escape Sequences em Strings](#escape-sequences-em-strings)
- [Strings Literais (Template Strings)](#Strings-Literais-template-strings)
- [String Métodos](#string-métodos)
- [Verificando Tipos de Dados e Casting](#verificando-tipos-de-dados-e-casting)
- [Verificando Tipos de Dados](#verificando-tipos-de-dados)
- [Mudando Tipo de Dado (Casting)](#mudando-tipo-de-dado-casting)
- [String para Int](#string-para-int)
- [String para Float](#string-para-float)
- [Float para Int](#float-para-int)
- [💻 Dia 2: Exercícios](#-dia-2-exercícios)
- [Exercícios: Level 1](#exercícios-level-1)
- [Exercícios: Level 2](#exercícios-level-2)
- [Exercícios: Level 3](#exercícios-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 dos dados, 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 ou 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 (não-modificável). Uma vez criado um tipo de dado primitivo nós não podemos mais modificá-lo.
**Exemplo:**
```js
let exemplo = 'JavaScript'
```
Se nós tentarmos modificar uma string armazenada na variável *exemplo*, o JavaScript irá mostar um error. Qualquer dado entre aspas simples, aspas duplas, ou crase é um string.
```js
exemplo[0] = 'Y'
```
Esta expressão não muda a string armazenada na variável *exemplo*. 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 numeroUm = 3
let numeroDois = 3
console.log(numeroUm == numeroDois) // verdadeiro
let js = 'JavaScript'
let py = 'Python'
console.log(js == py) // falso
let luzLigar = true
let luzApagar = false
console.log(luzLigar == luzApagar) // falso
```
### 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 diferentes 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 o terceiro elemento no index dois, etc.
```js
let numeros = [1, 2, 3]
numeros[0] = 1
console.log(numeros) // [1, 2, 3]
```
Como você pode ver, um array é um tipo de dado não primitivo e mutável. Tipos de dados não primitivos não 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 numeros = [1, 2, 3]
console.log(nums == numeros) // falso
let userOne = {
nome:'Asabeneh',
profissao:'professor',
país:'Finland'
}
let userTwo = {
nome:'Asabeneh',
profissao:'professor',
country:'Finland'
}
console.log(userOne == userTwo) // falso
```
Regra de ouro, nós não comparamos tipos de dados não primitivos. Não se compara arrays, funções, ou objetos. Porque eles são comparados pela sua referência 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 numeros = nums
console.log(nums == numeros) // verdadeiro
let userOne = {
nome:'Asabeneh',
profissao:'Professor',
país:'Finland'
}
let userTwo = userOne
console.log(userOne == userTwo) // verdadeiro
```
Com dificuldade de entender a diferença entre tipos de dados primitivos e tipos de dados não primitivos? Você não é o único. Calma e apenas vá para a próxima sessão e tente voltar aqui depois de algum tempo. Agora vamos começar com tipos de dados do tipo número.
## Números
Números são todos os inteiros e valores decimais que podem fazer todas as operações aritméticas.
Vamos ver alguns exemplos de Números.
### Declarando Tipos de Dados Numéricos
```js
let idade = 35
const gravidade = 9.81 // nós usamos const para valores que não mudam, constante gravitacional em 9,8 m/s².
let massa = 72 // massa em Kilogramas
const PI = 3.14 // pi constante geométrica
// Mais exemplos
const pontoEbulicao = 100 // temperatura em oC, ponto de ebulução da água que é uma constante
const temperaturaCorpo = 37 // oC média da temperatura corporal humana, que é uma constante
console.log(idade, gravidade, massa, PI, pontoEbulicao, temperaturaCorpo)
```
### Objeto Math
Em JavaScript o objeto Math promove muitos métodos para trabalhar com números.
```js
const PI = Math.PI
console.log(PI) // 3.141592653589793
// arredondando para o número mais próximo
// se maior que 0.5 para cima, se menor que 0.5 para baixo.
console.log(Math.round(PI)) // 3 é o valor mais próximo
console.log(Math.round(9.81)) // 10
console.log(Math.floor(PI)) // 3 arredondando para baixo
console.log(Math.ceil(PI)) // 4 arredondando para cima
console.log(Math.min(-5, 3, 20, 4, 5, 10)) // -5, retorna o valor mínimo
console.log(Math.max(-5, 3, 20, 4, 5, 10)) // 20, retorna o valor máximo
const numAleatorio = Math.random() // cria um número aleatório entre 0 até 0.999999
console.log(numAleatorio)
// Vamos criar um número aleatório entre 0 até 10
const num = Math.floor(Math.random () * 11) // cria um número aleatório entre 0 até 10
console.log(num)
// Valor absoluto
console.log(Math.abs(-10)) // 10
// Raiz quadrada
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) // 1.4142135623730951
// Potência
console.log(Math.pow(3, 2)) // 9
console.log(Math.E) // 2.718
// Logaritmo
// Retorna o logaritmo natural com base E de x, Math.log(x)
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
// Retorna o logaritmo natural de 2 e 10 repectivamente
console.log(Math.LN2) // 0.6931471805599453
console.log(Math.LN10) // 2.302585092994046
// Trigonometria
Math.sin(0)
Math.sin(60)
Math.cos(0)
Math.cos(60)
```
#### Gerador de Números Aleatórios
O objeto Math do JavaScript tem o método random() que gera números de 0 ate 0.999999999...
```js
let numeroAleatorio = Math.random() // gera de 0 até 0.999...
```
Agora, vamos ver como nós podemos usar o método random() para gerar um número aleatório entre 0 e 10:
```js
let numeroAleatorio = Math.random() // gera de 0 até 0.999
let numeroEntreZeroAteDez = numeroAleatorio * 11
console.log(numeroEntreZeroAteDez) // retorna: min 0 and max 10.99
let numeroAleatorioParaInteiro = Math.floor(numeroEntreZeroAteDez)
console.log(numeroAleatorioParaInteiro) // retorna: entre 0 e 10
```
## Strings
Strings são textos, que estão entre **_simples_**, **_duplas_**, **_crase_**. Para declarar uma string, nós precisamos de um nome de variável, operador de atribuição, um valor entre aspas simples, aspas duplas, ou crase.
Vamos ver alguns exemplos de string:
```js
let espaço = ' ' // um valor de string vazia
let primeiroNone = 'Asabeneh'
let ultimoNome = 'Yetayeh'
let país = 'Finland'
let cidade = 'Helsinki'
let linguagem = 'JavaScript'
let profissao = 'Professor'
let citacao = "The saying,'Seeing is Believing' is not correct in 2020."
let citacaoUsandoCrase = `The saying,'Seeing is Believing' is not correct in 2020.`
```
### String Concatenação
Conectando duas ou mais strings juntas é chamado de concatenação.
Usando as strings declaradas na sessão anterior de strings:
```js
let nomeCompleto = primeiroNone + espaco + ultimoNome; // concatenação, combinar duas ou mais strings juntas.
console.log(nomeCompleto);
```
```sh
Asabeneh Yetayeh
```
Nós podemos concatenar strings de jeitos diferentes.
#### Concatenando Usando o Operador de Adição
Concatenando usando o operador de adição é o modo antigo de fazer. Este tipo de concatenação é tedioso e propenso a erros. E é muito bom sabe como concatenar deste modo, mas eu sugiro fortemente que use o template ES6 de strings (explicado mais adiante).
```js
// Declarando diferentes variáveis de diferentes tipos de dados
let espaco = ' '
let primeiroNome = 'Asabeneh'
let ultimoNome = 'Yetayeh'
let pais = 'Finland'
let cidade = 'Helsinki'
let linguagem = 'JavaScript'
let profissao = 'teacher'
let idade = 250
let nomeCompleto = primeiroNome + espaco + ultimoNome
let pessoaUmInfo = nomeCompleto + '. I am ' + idade + '. I live in ' + país; // ES5 adição de string
console.log(pessoaUmInfo)
```
```sh
Asabeneh Yetayeh. I am 250. I live in Finland
```
### Strings Literais Longas
Uma string pode ser apenas um caractere, paragrafo ou uma página. Se o tamanho da string é maior que a linha. Nós podemos usar o caractere barras invertidas (\\) no final de cada linha para indicar que aquela string irá continuar na próxima linha.
**Exemplo**
```js
const paragrafo = "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(paragrafo)
```
#### Escape Sequences em Strings
Em JavaScript e outras linguagens de programação \ seguido de alguns caracteres, é um escape sequence. Vamos ver os mais usados:
- \n: Nova linha
- \t: Tab, significa 8 espaços
- \\\\: Barra
- \\': Single quote (')
- \\": Double quote (")
```js
console.log('I hope everyone is enjoying the 30 Days Of JavaScript challenge.\nDo you ?') // quebra de linha
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 (\\)') // Para mostar uma barra
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')
```
saída no 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
```
#### Strings Literais (Template Strings)
Para criar Strings Literais , nós usamos crases. Nós podemos injetar dados como expressões para criar String Literais, usando na expressão parentesis ({}) precedido de um sinal de dollar $. Veja a sintaxe abaixo.
```js
//Sintaxe
`String literal text`
`String literal text ${expressão}`
```
**Exemplo: 1**
```js
console.log(`The sum of 2 and 3 is 5`) // escrevendo dados estáticos
let a = 2
let b = 3
console.log(`The sum of ${a} and ${b} is ${a + b}`) // injetando dados dinamicamente
```
**Exemplo:2**
```js
let primeiroNome = 'Asabeneh'
let ultimoNome = 'Yetayeh'
let pais = 'Finland'
let cidade = 'Helsinki'
let linguagem = 'JavaScript'
let profissao = 'teacher'
let idade = 250
let nomeCompleto = primeiroNome + ' ' + ultimoNome
let pessoaInfoUm = `I am ${nomeCompleto}. I am ${idade}. I live in ${pais}.` //ES6 - Método de interpolação de String
let pesoaInfoDois = `I am ${nomeCompleto}. I live in ${cidade}, ${pais}. I am a ${profissao}. I teach ${linguagem}.`
console.log(pessoaInfoUm)
console.log(pesoaInfoDois)
```
```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.
```
Usando Literais ou método de interpolação de String, nós podemos adicionar expressões, que podem ser algum valor, ou alguma operação (comparação, aritimética, operador ternário).
```js
let a = 2
let b = 3
console.log(`${a} é maior que ${b}: ${a > b}`)
```
```sh
2 é maior que 3: false
```
### String Métodos
Tudo em JavaScript é um objeto. String é um tipo de dado primitivo, que significa que não podemos modificá-la uma vez criada. Um objeto String pode ter vários métodos. Existe diferentes métodos para strings que pode nos ajudar.
1. *length*: O método *length* retorna o número de caracteres em uma string incluindo espaços vázios.
**Exemplo:**
```js
let js = 'JavaScript'
console.log(js.length) // 10
let primeiroNome = 'Asabeneh'
console.log(primeiroNome.length) // 8
```
2. *Acessando caracteres em uma string*: Nós podemos acessar cada caractere em uma string usando seu index. Em programação, a contagem começa em 0. O primeiro index de uma string é zero, e o último index é o length de uma string - 1.
![Accessing string by index](../images/string_indexes.png)
Vamos acessar diferentes caracteres em 'JavaScript' string.
```js
let string = 'JavaScript'
let primeiraLetra = string[0]
console.log(primeiraLetra) // J
let segundaLetra = string[1] // a
let terceiraLetra = string[2]
let ultimaLetra = string[9]
console.log(ultimaLetra) // t
let ultimoIndex = string.length - 1
console.log(ultimoIndex) // 9
console.log(string[ultimoIndex]) // t
```
3. *toUpperCase()*: Este método muda a string para letras maiúsculas.
```js
let string = 'JavaScript'
console.log(string.toUpperCase()) // JAVASCRIPT
let primeiroNome = 'Asabeneh'
console.log(primeiroNome.toUpperCase()) // ASABENEH
let pais = 'Finland'
console.log(país.toUpperCase()) // FINLAND
```
4. *toLowerCase()*: Este método muda a string para letras minúsculas.
```js
let string = 'JavasCript'
console.log(string.toLowerCase()) // javascript
let primeiroNome = 'Asabeneh'
console.log(primeiroNome.toLowerCase()) // asabeneh
let pais = 'Finland'
console.log(pais.toLowerCase()) // finland
```
5. *substr()*: usando dois argumentos, o index de onde irá começar e o número de caracteres para retirar da string.
```js
let string = 'JavaScript'
console.log(string.substr(4,6)) // Script
let pais = 'Finland'
console.log(país.substr(3, 4)) // land
```
6. *substring()*: Usando dois argumentos, o index de onde irá começar e o index para parar, mas esse não inclui o caractere no index de parada.
```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 pais = 'Finland'
console.log(país.substring(0, 3)) // Fin
console.log(país.substring(3, 7)) // land
console.log(país.substring(3)) // land
```
7. *split()*: O método split divide uma string em um lugar especifico e converte em um array.
```js
let string = '30 Days Of JavaScript'
console.log(string.split()) // muda para um array -> ["30 Days Of JavaScript"]
console.log(string.split(' ')) // separa em um array com espaço -> ["30", "Days", "Of", "JavaScript"]
let primeiroNome = 'Asabeneh'
console.log(primeiroNome.split()) // muda para um array - > ["Asabeneh"]
console.log(primeiroNome.split('')) // separa em um array cada letra -> ["A", "s", "a", "b", "e", "n", "e", "h"]
let pais = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(país.split(',')) // separa para um array com vírgula -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(país.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
```
8. *trim()*: Remove espaços adicionais no início ou no final de uma string.
```js
let string = ' 30 Days Of JavaScript '
console.log(string)
console.log(string.trim(' '))
let primeiroNome = ' Asabeneh '
console.log(primeiroNome)
console.log(primeiroNome.trim()) // ainda remove espaços no início e no fim da string
```
```sh
30 Days Of JavasCript
30 Days Of JavasCript
Asabeneh
Asabeneh
```
9. *includes()*: Usando uma substring como argumento, e então verifica se o argumento exise na string. *includes()* retorna um boolean. Se uma substring existe na string, então retorna true, senão retornará false.
```js
let string = '30 Days Of JavaScript'
console.log(string.includes('Days')) // true
console.log(string.includes('days')) // false - é 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 pais = 'Finland'
console.log(país.includes('fin')) // false
console.log(país.includes('Fin')) // true
console.log(país.includes('land')) // true
console.log(país.includes('Land')) // false
```
10. *replace()*: Usando como parâmetro a antiga substring para uma nova substring.
```js
string.replace(antigaSubstring, novaSubstring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
let pais = 'Finland'
console.log(país.replace('Fin', 'Noman')) // Nomanland
```
11. *charAt()*: Usando um index e retorna o valor no index selecionado;
```js
string.charAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charAt(0)) // 3
let ultimoIndex = string.length - 1
console.log(string.charAt(ultimoIndex)) // t
```
12. *charCodeAt()*: Usando um index e retorna o código de caractere (número ASCII) do valor nesse index.
```js
string.charCodeAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charCodeAt(3)) // D ASCII número é 68
let ultimoIndex = string.length - 1
console.log(string.charCodeAt(ultimoIndex)) // t ASCII é 116
```
13. *indexOf()*: Usando uma substring e o mesmo existe em uma string retorna a primeira posição da substring, se não existe retornará -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()*: Usando uma substring e o mesmo existe em uma string retorna a última posição da substring, se não existe retornará -1
```js
//syntax
string.lastIndexOf(substring)
```
```js
let string = 'Eu amo JavaScript. Se você não ama JavaScript oque mais voce pode amar?'
console.log(string.lastIndexOf('love')) // 66
console.log(string.lastIndexOf('you')) // 56
console.log(string.lastIndexOf('JavaScript')) // 35
```
15. *concat()*: Usando algumas substring e os adiciona (Join).
```js
string.concat(substring, substring, substring)
```
```js
let string = '30'
console.log(string.concat(" Days ", "Of", " JavaScript")) // 30 Days Of JavaScript
let country = 'Fin'
console.log(country.concat("land")) // Finland
```
16. *startsWith*: Usando uma substring como argumento, e verifica se a string começa com aquela substring específica. E retorna um boolean(true ou 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*: Usando uma substring como argumento, e verifica se a string termina com aquela substring específica. E retorna um boolean(true ou 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 pais = 'Finland'
console.log(país.endsWith('land')) // true
console.log(país.endsWith('fin')) // false
console.log(país.endsWith('Fin')) // false
```
18. *search*: Usando uma substring como um argumento e retorna o index do primeiro resultado. O valor da pesquisa pode ser uma string ou uma expressão regular.
```js
string.search(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2
console.log(string.search(/javascript/gi)) // 7
```
19. *match*: Usando uma substring ou expressão regular como um argumento, e retorna um array se exite um resultado, se nao retorna null. Vamos ver como uma expressão regular se parece. Começa com / sinal e terminar com / sinal.
```js
let string = 'love'
let patternOne = /love/ // sem nenhuma flag
let patternTwo = /love/gi // g-significa procurar em todo o texto, i - case insensitive
```
Sintaxe
```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.", grupo: undefined]
```
```js
let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
```
"Vamos extrair números de um texto usando uma expressão regular. Essa não é a seção de expressões regulares, não se assuste! Vamos cobrir expressões regulares mais tarde."
```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+/
// A letra 'd' com o caractere de escape significa 'd' não como uma letra normal, mas sim como um dígito.
// O sinal '+' significa um ou mais números de dígitos,
// Se houver a letra 'g' depois disso, significa global, pesquisar em todos os lugares.
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
```
20. *repeat()*: Um número como argumento e retorna uma versão repetida de uma string.
```js
string.repeat(n)
```
```js
let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
```
## Verificando Tipos de Dados e Casting
### Verificando Tipos de Dados
Para verificar o tipo de uma variável nós usamos o método _typeOf_.
**Exemplo:**
```js
// Diferente tipos de dados javascript
// vamos declarar diferentes tipos de dados
let primeiroNome = 'Asabeneh' // string
let ultimoNome = 'Yetayeh' // string
let pais = 'Finland' // string
let cidade = 'Helsinki' // string
let idade = 250 // número, não é minha idade real, não se preocupe com isso
let profissao // undefined, porque o valor não foi definido.
console.log(typeof 'Asabeneh') // string
console.log(typeof primeiroNome) // 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 profissao) // undefined
console.log(typeof undefined) // undefined
console.log(typeof null) // object
```
### Mudando Tipo de Dado (Casting)
- Casting: Convertendo um tipo de dados para outro. Usamos _parseInt()_, _parseFloat()_, _Number()_, _+ sign_ +, _str()_
Quando fazemos operações aritméticas, os números em forma de string devem ser primeiro convertidos em inteiros ou floats, caso contrário, ocorre um erro.
#### String para Int
Podemos converter números em forma de string para um número. Qualquer número dentro de aspas é um número em forma de string. Um exemplo de número em forma de string: '10', '5', etc.
Podemos converter uma string para um número usando os seguintes métodos:
- 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 para Float
Nós podemos converter uma string float número para um número float. Qualquer número float entre aspas é uma string float número. Exemplo:
'9.81', '3.14', '1.44', etc.
Podemos converter string float número usando os seguintes métodos:
- 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 para Int
Podemos converter float números para inteiro.
Vamos usar o seguinte método para converter float para int.
- parseInt()
```js
let num = 9.81
let numInt = parseInt(num)
console.log(numInt) // 9
```
🌕 Você é incrível. Você acabou de completar o dia 2 e está dois passos a frente no seu caminho para o sucesso. Agora faça alguns exercícios para seu cérebro e músculos.
## 💻 Dia 2: Exercícios
### Exercícios: Level 1
1. Declare uma variável chamada desafio e atribua a ela um valor inicial **'30 Dias de JavaScript'**.
2. Imprimir uma string no console do browser usando __console.log()__ .
3. Imprimir o __length__ da string no console do browser usando o __console.log()__.
4. Troque todos os caracteres da string para letras maiúsculas usando o método __toUpperCase()__.
5. Troque todos os caracteres da string para letras minúsculas usando o método __toLowerCase()__.
6. Retirar (Slice) a primeira letra da string usando os métodos __substr()__ ou __substring()__.
7. Dividir a frase *Days Of JavaScript* de *30 Days Of JavaScript*.
8. Verificar se a string contém a palavra __Script__ usando o método __includes()__.
9. Separar a __string__ em um __array__ usando o método __split()__.
10. Separar a string 30 Dias de JavaScript com espaços usando o método __split()__.
11. "Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon" __split__ a string com vírgulas e mude-a para um array.
12. Mude 30 Dias de JavaScript para 30 Dias de Python usando o método __replace()__.
13. Qual é o caractere no index 15 em "30 Dias de JavaScript' string? Use o método __charAt()__.
14. Qual é o código do caractere de J em "30 Dias de JavaScript" string usando o método __charCodeAt()__.
15. Use __indexOf__ para determinar a posição da primeira ocorrência de __a__ em 30 Dias de JavaScript.
16. Use __lastIndexOf__ para determinar a posição da última ocorrência de __a__ em 30 Dias de JavaScript.
17. Use __indexOf__ para encontrar a posição da primeira ocorrência da palavra __because__ na seguinte frase:__'You cannot end a sentence with because because because is a conjunction'__.
18. Use __lastIndexOf__ para encontrar a posição da última ocorrência da palavra __because__ na seguinte frase:__'You cannot end a sentence with because because because is a conjunction'__.
19. Use __search__ para encontrar a posição da primeira ocorrência da palavra __because__ na seguinte frase:__'You cannot end a sentence with because because because is a conjunction'__.
20. Use __trim()__ para remover qualquer espaço adicional no início e no final da string .E.g " 30 Dias de JavaScript ".
21. Use __startsWith()__ com a string *30 Dias De JavaScript* e faça o resultado ser verdadeiro.
22. Use __endsWith()__ com a string *30 Dias De JavaScript* e faça o resultado ser verdadeiro.
23. Use __match()__ para encontrar todos os __a__'s em 30 Dias De JavaScript.
24. Use __concat()__ para unir "30 Dias de" e "JavaScript" para uma única string, "30 Dias de JavaScript".
25. Use __repeat()__ para imprimir 30 Dias De JavaScript 2 vezes.
### Exercícios: Level 2
1. Usando o console.log() imprimir a seguinte citação:
```sh
"Não há exercício melhor para o coração que ir lá em baixo e levantar as pessoas" by John Holmes nos ensina a ajudar outras pessoas.
```
2. Usando o console.log() imprimir a seguinte citação de Madre Teresa:
```sh
"O amor não é paternalista e a caridade não tem a ver com pena, tem a ver com amor. Caridade e amor são a mesma coisa com a caridade você dá amor, então não dê apenas dinheiro, mas estenda sua mão."
```
3. Verificar se typeOf "10" é exatamente igual a 10. Se não, faça ser exatamente igual.
4. Verificar se parseFloat("9.8) é igual a 10. Se não, faça ser exatamente igual com 10.
5. Verificar se "ão" é encontrado em ambos algodão e jargão.
6. _Espero que este curso não tenha muitos jargões_. Verifique se _jargões_ está na frase.
7. Gerar um número aleatório entre incluindo 0 e 100.
8. Gerar um número aleatório entre incluindo 50 e 100.
9. Gerar um número aleatório entre incluindo 0 e 255.
10. Acesse os caracteres da string "JavaScript" usando um número aleatório.
11. Use console.log() e imprimir os caracteres no seguinte padrão.
```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__ para retirar da frase __because because because__ da seguinte frase: __'You cannot end a sentence with because because because is a conjunction'__.
### Exercícios: Level 3
1. "Amor é a melhor coisa neste mundo. Alguns encontraram seu amor e alguns ainda estão procurando pelo seu amor." Contar o número de palavras __amor__ nesta frase.
2. Use __match()__ para contar os números de todos os __because__ na seguinte frase: __'You cannot end a sentence with because because because is a conjunction'__.
3. Limpar o seguinte texto e encontrar a palavra mais repetida (dica, use replace e expressões regulares)
```js
const frase = " %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. Calcular o total anual de uma pessoa extraindo os números do seguinte texto. __"Ele recebe 5000 euros de salário por mês, 10000 euros de bônus anual, 15000 euros de cursos onlines por mês.'__.
🎉 PARABÉNS ! 🎉
[<< Dia 1](../readMe.md) | [Dia 3 >>](../Dia_03_Booleanos_Operadores_Data/dia_03_booleanos_operadores_data.md)

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>30DaysOfJavaScript: 03 Day</title>
</head>
<body>
<h1>30DaysOfJavaScript:03 Day</h1>
<h2>Booleans, undefined, null, date object</h2>
<!-- import your scripts here -->
<script src="./scripts/main.js"></script>
</body>
</html>

@ -0,0 +1,633 @@
<div align="center">
<h1> 30 Dias De JavaScript: Boleanos, Operadores e Data</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor;
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Janeiro, 2020</small>
</sub>
</div>
[<< Day 2](../Dia_02_Tipos_Dados/dia_02_tipos_dados.md) | [Day 4 >>](../04_Day_Conditionals/04_day_conditionals.md)
![Thirty Days Of JavaScript](../images/banners/day_1_3.png)
- [📔 Day 3](#-day-3)
- [Booleans](#booleans)
- [Truthy values](#truthy-values)
- [Falsy values](#falsy-values)
- [Undefined](#undefined)
- [Null](#null)
- [Operators](#operators)
- [Assignment operators](#assignment-operators)
- [Arithmetic Operators](#arithmetic-operators)
- [Comparison Operators](#comparison-operators)
- [Logical Operators](#logical-operators)
- [Increment Operator](#increment-operator)
- [Decrement Operator](#decrement-operator)
- [Ternary Operators](#ternary-operators)
- [Operator Precedence](#operator-precedence)
- [Window Methods](#window-methods)
- [Window alert() method](#window-alert-method)
- [Window prompt() method](#window-prompt-method)
- [Window confirm() method](#window-confirm-method)
- [Date Object](#date-object)
- [Creating a time object](#creating-a-time-object)
- [Getting full year](#getting-full-year)
- [Getting month](#getting-month)
- [Getting date](#getting-date)
- [Getting day](#getting-day)
- [Getting hours](#getting-hours)
- [Getting minutes](#getting-minutes)
- [Getting seconds](#getting-seconds)
- [Getting time](#getting-time)
- [💻 Day 3: Exercises](#-day-3-exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# 📔 Day 3
## Booleans
A boolean data type represents one of the two values:_true_ or _false_. Boolean value is either true or false. The use of these data types will be clear when you start the comparison operator. Any comparisons return a boolean value which is either true or false.
**Example: Boolean Values**
```js
let isLightOn = true
let isRaining = false
let isHungry = false
let isMarried = true
let truValue = 4 > 3 // true
let falseValue = 4 < 3 // false
```
We agreed that boolean values are either true or false.
### Truthy values
- All numbers(positive and negative) are truthy except zero
- All strings are truthy except an empty string ('')
- The boolean true
### Falsy values
- 0
- 0n
- null
- undefined
- NaN
- the boolean false
- '', "", ``, empty string
It is good to remember those truthy values and falsy values. In later section, we will use them with conditions to make decisions.
## Undefined
If we declare a variable and if we do not assign a value, the value will be undefined. In addition to this, if a function is not returning the value, it will be undefined.
```js
let firstName
console.log(firstName) //not defined, because it is not assigned to a value yet
```
## Null
```js
let empty = null
console.log(empty) // -> null , means no value
```
## Operators
### Assignment operators
An equal sign in JavaScript is an assignment operator. It uses to assign a variable.
```js
let firstName = 'Asabeneh'
let country = 'Finland'
```
Assignment Operators
![Assignment operators](../images/assignment_operators.png)
### Arithmetic Operators
Arithmetic operators are mathematical operators.
- Addition(+): a + b
- Subtraction(-): a - b
- Multiplication(*): a * b
- Division(/): a / b
- Modulus(%): a % b
- Exponential(**): a ** b
```js
let numOne = 4
let numTwo = 3
let sum = numOne + numTwo
let diff = numOne - numTwo
let mult = numOne * numTwo
let div = numOne / numTwo
let remainder = numOne % numTwo
let powerOf = numOne ** numTwo
console.log(sum, diff, mult, div, remainder, powerOf) // 7,1,12,1.33,1, 64
```
```js
const PI = 3.14
let radius = 100 // length in meter
//Let us calculate area of a circle
const areaOfCircle = PI * radius * radius
console.log(areaOfCircle) // 314 m
const gravity = 9.81 // in m/s2
let mass = 72 // in Kilogram
// Let us calculate weight of an object
const weight = mass * gravity
console.log(weight) // 706.32 N(Newton)
const boilingPoint = 100 // temperature in oC, boiling point of water
const bodyTemp = 37 // body temperature in oC
// Concatenating string with numbers using string interpolation
/*
The boiling point of water is 100 oC.
Human body temperature is 37 oC.
The gravity of earth is 9.81 m/s2.
*/
console.log(
`The boiling point of water is ${boilingPoint} oC.\nHuman body temperature is ${bodyTemp} oC.\nThe gravity of earth is ${gravity} m / s2.`
)
```
### Comparison Operators
In programming we compare values, we use comparison operators to compare two values. We check if a value is greater or less or equal to other value.
![Comparison Operators](../images/comparison_operators.png)
**Example: Comparison Operators**
```js
console.log(3 > 2) // true, because 3 is greater than 2
console.log(3 >= 2) // true, because 3 is greater than 2
console.log(3 < 2) // false, because 3 is greater than 2
console.log(2 < 3) // true, because 2 is less than 3
console.log(2 <= 3) // true, because 2 is less than 3
console.log(3 == 2) // false, because 3 is not equal to 2
console.log(3 != 2) // true, because 3 is not equal to 2
console.log(3 == '3') // true, compare only value
console.log(3 === '3') // false, compare both value and data type
console.log(3 !== '3') // true, compare both value and data type
console.log(3 != 3) // false, compare only value
console.log(3 !== 3) // false, compare both value and data type
console.log(0 == false) // true, equivalent
console.log(0 === false) // false, not exactly the same
console.log(0 == '') // true, equivalent
console.log(0 == ' ') // true, equivalent
console.log(0 === '') // false, not exactly the same
console.log(1 == true) // true, equivalent
console.log(1 === true) // false, not exactly the same
console.log(undefined == null) // true
console.log(undefined === null) // false
console.log(NaN == NaN) // false, not equal
console.log(NaN === NaN) // false
console.log(typeof NaN) // number
console.log('mango'.length == 'avocado'.length) // false
console.log('mango'.length != 'avocado'.length) // true
console.log('mango'.length < 'avocado'.length) // true
console.log('milk'.length == 'meat'.length) // true
console.log('milk'.length != 'meat'.length) // false
console.log('tomato'.length == 'potato'.length) // true
console.log('python'.length > 'dragon'.length) // false
```
Try to understand the above comparisons with some logic. Remembering without any logic might be difficult.
JavaScript is somehow a wired kind of programming language. JavaScript code run and give you a result but unless you are good at it may not be the desired result.
As rule of thumb, if a value is not true with == it will not be equal with ===. Using === is safer than using ==. The following [link](https://dorey.github.io/JavaScript-Equality-Table/) has an exhaustive list of comparison of data types.
### Logical Operators
The following symbols are the common logical operators:
&&(ampersand) , ||(pipe) and !(negation).
The && operator gets true only if the two operands are true.
The || operator gets true either of the operand is true.
The ! operator negates true to false and false to true.
```js
// && ampersand operator example
const check = 4 > 3 && 10 > 5 // true && true -> true
const check = 4 > 3 && 10 < 5 // true && false -> false
const check = 4 < 3 && 10 < 5 // false && false -> false
// || pipe or operator, example
const check = 4 > 3 || 10 > 5 // true || true -> true
const check = 4 > 3 || 10 < 5 // true || false -> true
const check = 4 < 3 || 10 < 5 // false || false -> false
//! Negation examples
let check = 4 > 3 // true
let check = !(4 > 3) // false
let isLightOn = true
let isLightOff = !isLightOn // false
let isMarried = !false // true
```
### Increment Operator
In JavaScript we use the increment operator to increase a value stored in a variable. The increment could be pre or post increment. Let us see each of them:
1. Pre-increment
```js
let count = 0
console.log(++count) // 1
console.log(count) // 1
```
1. Post-increment
```js
let count = 0
console.log(count++) // 0
console.log(count) // 1
```
We use most of the time post-increment. At least you should remember how to use post-increment operator.
### Decrement Operator
In JavaScript we use the decrement operator to decrease a value stored in a variable. The decrement could be pre or post decrement. Let us see each of them:
1. Pre-decrement
```js
let count = 0
console.log(--count) // -1
console.log(count) // -1
```
2. Post-decrement
```js
let count = 0
console.log(count--) // 0
console.log(count) // -1
```
### Ternary Operators
Ternary operator allows to write a condition.
Another way to write conditionals is using ternary operators. Look at the following examples:
```js
let isRaining = true
isRaining
? console.log('You need a rain coat.')
: console.log('No need for a rain coat.')
isRaining = false
isRaining
? console.log('You need a rain coat.')
: console.log('No need for a rain coat.')
```
```sh
You need a rain coat.
No need for a rain coat.
```
```js
let number = 5
number > 0
? console.log(`${number} is a positive number`)
: console.log(`${number} is a negative number`)
number = -5
number > 0
? console.log(`${number} is a positive number`)
: console.log(`${number} is a negative number`)
```
```sh
5 is a positive number
-5 is a negative number
```
### Operator Precedence
I would like to recommend you to read about operator precedence from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
## Window Methods
### Window alert() method
As you have seen at very beginning alert() method displays an alert box with a specified message and an OK button. It is a builtin method and it takes on argument.
```js
alert(message)
```
```js
alert('Welcome to 30DaysOfJavaScript')
```
Do not use too much alert because it is destructing and annoying, use it just to test.
### Window prompt() method
The window prompt methods display a prompt box with an input on your browser to take input values and the input data can be stored in a variable. The prompt() method takes two arguments. The second argument is optional.
```js
prompt('required text', 'optional text')
```
```js
let number = prompt('Enter number', 'number goes here')
console.log(number)
```
### Window confirm() method
The confirm() method displays a dialog box with a specified message, along with an OK and a Cancel button.
A confirm box is often used to ask permission from a user to execute something. Window confirm() takes a string as an argument.
Clicking the OK yields true value, whereas clicking the Cancel button yields false value.
```js
const agree = confirm('Are you sure you like to delete? ')
console.log(agree) // result will be true or false based on what you click on the dialog box
```
These are not all the window methods we will have a separate section to go deep into window methods.
## Date Object
Time is an important thing. We like to know the time a certain activity or event. In JavaScript current time and date is created using JavaScript Date Object. The object we create using Date object provides many methods to work with date and time.The methods we use to get date and time information from a date object values are started with a word _get_ because it provide the information.
_getFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_
![Date time Object](../images/date_time_object.png)
### Creating a time object
Once we create time object. The time object will provide information about time. Let us create a time object
```js
const now = new Date()
console.log(now) // Sat Jan 04 2020 00:56:41 GMT+0200 (Eastern European Standard Time)
```
We have created a time object and we can access any date time information from the object using the get methods we have mentioned on the table.
### Getting full year
Let's extract or get the full year from a time object.
```js
const now = new Date()
console.log(now.getFullYear()) // 2020
```
### Getting month
Let's extract or get the month from a time object.
```js
const now = new Date()
console.log(now.getMonth()) // 0, because the month is January, month(0-11)
```
### Getting date
Let's extract or get the date of the month from a time object.
```js
const now = new Date()
console.log(now.getDate()) // 4, because the day of the month is 4th, day(1-31)
```
### Getting day
Let's extract or get the day of the week from a time object.
```js
const now = new Date()
console.log(now.getDay()) // 6, because the day is Saturday which is the 7th day
// Sunday is 0, Monday is 1 and Saturday is 6
// Getting the weekday as a number (0-6)
```
### Getting hours
Let's extract or get the hours from a time object.
```js
const now = new Date()
console.log(now.getHours()) // 0, because the time is 00:56:41
```
### Getting minutes
Let's extract or get the minutes from a time object.
```js
const now = new Date()
console.log(now.getMinutes()) // 56, because the time is 00:56:41
```
### Getting seconds
Let's extract or get the seconds from a time object.
```js
const now = new Date()
console.log(now.getSeconds()) // 41, because the time is 00:56:41
```
### Getting time
This method give time in milliseconds starting from January 1, 1970. It is also know as Unix time. We can get the unix time in two ways:
1. Using _getTime()_
```js
const now = new Date() //
console.log(now.getTime()) // 1578092201341, this is the number of seconds passed from January 1, 1970 to January 4, 2020 00:56:41
```
1. Using _Date.now()_
```js
const allSeconds = Date.now() //
console.log(allSeconds) // 1578092201341, this is the number of seconds passed from January 1, 1970 to January 4, 2020 00:56:41
const timeInSeconds = new Date().getTime()
console.log(allSeconds == timeInSeconds) // true
```
Let us format these values to a human readable time format.
**Example:**
```js
const now = new Date()
const year = now.getFullYear() // return year
const month = now.getMonth() + 1 // return month(0 - 11)
const date = now.getDate() // return date (1 - 31)
const hours = now.getHours() // return number (0 - 23)
const minutes = now.getMinutes() // return number (0 -59)
console.log(`${date}/${month}/${year} ${hours}:${minutes}`) // 4/1/2020 0:56
```
🌕 You have boundless energy. You have just completed day 3 challenges and you are three steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## 💻 Day 3: Exercises
### Exercises: Level 1
1. Declare firstName, lastName, country, city, age, isMarried, year variable and assign value to it and use the typeof operator to check different data types.
2. Check if type of '10' is equal to 10
3. Check if parseInt('9.8') is equal to 10
4. Boolean value is either true or false.
1. Write three JavaScript statement which provide truthy value.
2. Write three JavaScript statement which provide falsy value.
5. Figure out the result of the following comparison expression first without using console.log(). After you decide the result confirm it using console.log()
1. 4 > 3
2. 4 >= 3
3. 4 < 3
4. 4 <= 3
5. 4 == 4
6. 4 === 4
7. 4 != 4
8. 4 !== 4
9. 4 != '4'
10. 4 == '4'
11. 4 === '4'
12. Find the length of python and jargon and make a falsy comparison statement.
6. Figure out the result of the following expressions first without using console.log(). After you decide the result confirm it by using console.log()
1. 4 > 3 && 10 < 12
2. 4 > 3 && 10 > 12
3. 4 > 3 || 10 < 12
4. 4 > 3 || 10 > 12
5. !(4 > 3)
6. !(4 < 3)
7. !(false)
8. !(4 > 3 && 10 < 12)
9. !(4 > 3 && 10 > 12)
10. !(4 === '4')
11. There is no 'on' in both dragon and python
7. Use the Date object to do the following activities
1. What is the year today?
2. What is the month today as a number?
3. What is the date today?
4. What is the day today as a number?
5. What is the hours now?
6. What is the minutes now?
7. Find out the numbers of seconds elapsed from January 1, 1970 to now.
### Exercises: Level 2
1. Write a script that prompt the user to enter base and height of the triangle and calculate an area of a triangle (area = 0.5 x b x h).
```sh
Enter base: 20
Enter height: 10
The area of the triangle is 100
```
1. Write a script that prompt the user to enter side a, side b, and side c of the triangle and and calculate the perimeter of triangle (perimeter = a + b + c)
```sh
Enter side a: 5
Enter side b: 4
Enter side c: 3
The perimeter of the triangle is 12
```
1. Get length and width using prompt and calculate an area of rectangle (area = length x width and the perimeter of rectangle (perimeter = 2 x (length + width))
1. Get radius using prompt and calculate the area of a circle (area = pi x r x r) and circumference of a circle(c = 2 x pi x r) where pi = 3.14.
1. Calculate the slope, x-intercept and y-intercept of y = 2x -2
1. Slope is m = (y<sub>2</sub>-y<sub>1</sub>)/(x<sub>2</sub>-x<sub>1</sub>). Find the slope between point (2, 2) and point(6,10)
1. Compare the slope of above two questions.
1. Calculate the value of y (y = x<sup>2</sup> + 6x + 9). Try to use different x values and figure out at what x value y is 0.
1. Writ a script that prompt a user to enter hours and rate per hour. Calculate pay of the person?
```sh
Enter hours: 40
Enter rate per hour: 28
Your weekly earning is 1120
```
1. If the length of your name is greater than 7 say, your name is long else say your name is short.
1. Compare your first name length and your family name length and you should get this output.
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
```
```sh
Your first name, Asabeneh is longer than your family name, Yetayeh
```
1. Declare two variables _myAge_ and _yourAge_ and assign them initial values and myAge and yourAge.
```js
let myAge = 250
let yourAge = 25
```
```sh
I am 225 years older than you.
```
1. Using prompt get the year the user was born and if the user is 18 or above allow the user to drive if not tell the user to wait a certain amount of years.
```sh
Enter birth year: 1995
You are 25. You are old enough to drive
Enter birth year: 2005
You are 15. You will be allowed to drive after 3 years.
```
1. Write a script that prompt the user to enter number of years. Calculate the number of seconds a person can live. Assume some one lives just hundred years
```sh
Enter number of years you live: 100
You lived 3153600000 seconds.
```
1. Create a human readable time format using the Date time object
1. YYYY-MM-DD HH:mm
2. DD-MM-YYYY HH:mm
3. DD/MM/YYYY HH:mm
### Exercises: Level 3
1. Create a human readable time format using the Date time object. The hour and the minute should be all the time two digits(7 hours should be 07 and 5 minutes should be 05 )
1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05
[<< Dia 2](../Dia_02_Tipos_Dados/dia_02_tipos_dados.md) | [Dia 4 >>](../04_Day_Conditionals/04_day_conditionals.md)

@ -649,7 +649,7 @@ Quando você executa o arquivo _index.html_ na pasta dia-1 você deve conseguir
![Day one](/images/day_1.png)
🌕 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.
🌕 Você é incrivel! Você acabou de completar o desafio do dia 1 e você está no seu caminho para o sucesso. Agora faça alguns exercícios para seu cérebro e músculos.
# 💻 Dia 1: Exercícios
@ -671,4 +671,4 @@ You are 30 years old.
🎉 PARABÉNS ! 🎉
[Dia 2 >>](./02_Day_Data_types/02_day_data_types.md)
[Dia 2 >>](./Dia_02_Tipos_Dados/dia_02_tipos_dados.md)

Loading…
Cancel
Save