Lessons from day 1 to day 7 have been translated in Italian for one more language support.pull/365/head
parent
2d2baae288
commit
bd3d962f9b
@ -0,0 +1,634 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Booleans, Operators, Date</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 2](../02_Day_Data_types/02_day_data_types.md) | [Day 4 >>](../04_Day_Conditionals/04_day_conditionals.md)
|
||||
|
||||

|
||||
|
||||
- [📔 Giorno 3](#-day-3)
|
||||
- [Booleans](#booleans)
|
||||
- [Valori Che Restituiscono True](#truthy-values)
|
||||
- [Valori Che Restituiscono False](#falsy-values)
|
||||
- [Undefined](#undefined)
|
||||
- [Null](#null)
|
||||
- [Operatori](#operators)
|
||||
- [Operatori di Assegnamento](#assignment-operators)
|
||||
- [Operatori Aritmetici](#arithmetic-operators)
|
||||
- [Operatori di Confronto](#comparison-operators)
|
||||
- [Operatori Logici](#logical-operators)
|
||||
- [Operatore d'Incremento](#increment-operator)
|
||||
- [Operatore di Decremento](#decrement-operator)
|
||||
- [Operatori Ternari](#ternary-operators)
|
||||
- [Precedenza dell'Operatore](#operator-precedence)
|
||||
- [Metodi delle finestre (Window)](#window-methods)
|
||||
- [Window alert()](#window-alert-method)
|
||||
- [Window prompt()](#window-prompt-method)
|
||||
- [Window confirm()](#window-confirm-method)
|
||||
- [Oggetto Date](#date-object)
|
||||
- [Creare un oggetto data (time)](#creating-a-time-object)
|
||||
- [Ottenere Valore Anno](#getting-full-year)
|
||||
- [Ottenere Valore mese](#getting-month)
|
||||
- [Ottenere Valore data](#getting-date)
|
||||
- [Ottenere Valore giorno](#getting-day)
|
||||
- [Ottenere Valore ora](#getting-hours)
|
||||
- [Ottenere Valore minuto](#getting-minutes)
|
||||
- [Ottenere Valore secondo](#getting-seconds)
|
||||
- [Ottenere Valore tempo](#getting-time)
|
||||
- [💻 Day 3: Esercizi](#-day-3-exercises)
|
||||
- [Esercizi: Livello 1](#exercises-level-1)
|
||||
- [Esercizi: Livello 2](#exercises-level-2)
|
||||
- [Esercizi: Livello 3](#exercises-level-3)
|
||||
|
||||
# 📔 Giorno 3
|
||||
|
||||
## Booleans
|
||||
|
||||
Un tipo di dati booleano rappresenta uno dei due valori: _true_ o _false_. Il valore booleano è o vero o falso. L'uso di questi tipi di dati sarà chiaro quando si inizierà a utilizzare l'operatore di confronto. Qualsiasi confronto restituisce un valore booleano che può essere vero o falso.
|
||||
|
||||
**Esempio: Valori Boolean**
|
||||
|
||||
```js
|
||||
let isLightOn = true
|
||||
let isRaining = false
|
||||
let isHungry = false
|
||||
let isMarried = true
|
||||
let truValue = 4 > 3 // true
|
||||
let falseValue = 4 < 3 // false
|
||||
```
|
||||
|
||||
Abbiamo concordato che i valori booleani sono veri o falsi.
|
||||
|
||||
### Valori Che Resituiscono True
|
||||
|
||||
- Tutti i numeri (positivi e negativi) sono veri, tranne lo zero.
|
||||
- Tutte le stringhe sono vere, tranne una stringa vuota ('')
|
||||
- Il boolean true
|
||||
|
||||
### Valori Che Resituiscono False
|
||||
|
||||
- 0
|
||||
- 0n
|
||||
- null
|
||||
- undefined
|
||||
- NaN
|
||||
- il boolean false
|
||||
- '', "", ``, empty string
|
||||
|
||||
È bene ricordare questi valori veri e falsi. Nella sezione successiva, li useremo con le condizioni per prendere decisioni.
|
||||
|
||||
## Undefined
|
||||
|
||||
Se dichiariamo una variabile e non le assegniamo un valore, il valore sarà indefinito. Inoltre, se una funzione non restituisce il valore, sarà 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
|
||||
```
|
||||
|
||||
## Operatori
|
||||
|
||||
### Operatori di Assegnamento
|
||||
|
||||
An equal sign in JavaScript is an assignment operator. It uses to assign a variable.
|
||||
|
||||
```js
|
||||
let firstName = 'Asabeneh'
|
||||
let country = 'Finland'
|
||||
```
|
||||
|
||||
Operatori di Assegnamento
|
||||
|
||||

|
||||
|
||||
### Operatori Aritmetici
|
||||
|
||||
Gli operatori aritmetici sono operatori matematici.
|
||||
|
||||
- Addizione(+): a + b
|
||||
- Sottrazione(-): a - b
|
||||
- Moltiplicazione(*): a * b
|
||||
- Divisione(/): a / b
|
||||
- Modulo(%): a % b
|
||||
- Esponenziale(**): 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.`
|
||||
)
|
||||
```
|
||||
|
||||
### Operatori di Confronto
|
||||
|
||||
Nella programmazione si confrontano i valori, utilizzando gli operatori di confronto per confrontare due valori. Controlliamo se un valore è maggiore o minore o uguale a un altro valore.
|
||||
|
||||

|
||||
**Esempio: Operatori di Confronto**
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Cerca di capire i confronti di cui sopra con un po' di logica. Ricorda, senza alcuna logica potrebbe essere difficile.
|
||||
JavaScript è in qualche modo un linguaggio di programmazione cablato. Il codice JavaScript viene eseguito e fornisce un risultato, ma se non si è attenti, potrebbe non essere il risultato desiderato.
|
||||
|
||||
Come regola generale, se un valore non è vero con ==, non sarà uguale con ===. L'uso di === è più sicuro di quello di ==. Il seguente [link](https://dorey.github.io/JavaScript-Equality-Table/) contiene un elenco esaustivo di confronti tra tipi di dati.
|
||||
|
||||
|
||||
### Operatori Logici
|
||||
|
||||
I seguenti simboli sono gli operatori logici comuni:
|
||||
&& (ampersand), || (pipe) e ! (negazione).
|
||||
L'operatore && diventa vero solo se i due operandi sono veri.
|
||||
L'operatore || diventa vero se entrambi gli operandi sono veri.
|
||||
L'operatore ! nega il vero al falso e il falso al vero.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
### Operatore d'Incremento
|
||||
|
||||
In JavaScript si usa l'operatore di incremento per aumentare un valore memorizzato in una variabile. L'incremento può essere pre o post incremento. Vediamo i due tipi di incremento:
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
Nella maggior parte dei casi utilizziamo l'operatore post-incremento. Dovreste almeno ricordare come si usa l'operatore post-incremento.
|
||||
|
||||
### Operatore di Decremento
|
||||
|
||||
In JavaScript si usa l'operatore decremento per diminuire un valore memorizzato in una variabile. Il decremento può essere pre o post decremento. Vediamo ciascuno di essi:
|
||||
|
||||
1. Pre-decremento
|
||||
|
||||
```js
|
||||
let count = 0
|
||||
console.log(--count) // -1
|
||||
console.log(count) // -1
|
||||
```
|
||||
|
||||
2. Post-decremento
|
||||
|
||||
```js
|
||||
let count = 0
|
||||
console.log(count--) // 0
|
||||
console.log(count) // -1
|
||||
```
|
||||
|
||||
### Operatori Ternari
|
||||
|
||||
L'operatore ternario permette di scrivere una condizione.
|
||||
Un altro modo per scrivere le condizioni è utilizzare gli operatori ternari. Guardate i seguenti esempi:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
### Precedenza dell'Operatore
|
||||
|
||||
Vorrei raccomandare di leggere le informazioni sulla precedenza degli operatori da questo documento [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
|
||||
|
||||
## Metodi delle finestre (Window)
|
||||
|
||||
### Window alert()
|
||||
|
||||
Come si è visto all'inizio, il metodo alert() visualizza una casella di avviso con un messaggio specificato e un pulsante OK. Si tratta di un metodo integrato che richiede un solo argomento.
|
||||
|
||||
```js
|
||||
alert(message)
|
||||
```
|
||||
|
||||
```js
|
||||
alert('Welcome to 30DaysOfJavaScript')
|
||||
```
|
||||
|
||||
Non utilizzare un'allerta eccessiva perché è distruttiva e fastidiosa, usarla solo per fare delle prove.
|
||||
|
||||
### Window prompt()
|
||||
|
||||
I metodi di prompt della finestra visualizzano una casella di prompt con un input sul browser per accettare valori di input e i dati di input possono essere memorizzati in una variabile. Il metodo prompt() accetta due argomenti. Il secondo argomento è opzionale.
|
||||
|
||||
```js
|
||||
prompt('required text', 'optional text')
|
||||
```
|
||||
|
||||
```js
|
||||
let number = prompt('Enter number', 'number goes here')
|
||||
console.log(number)
|
||||
```
|
||||
|
||||
### Window confirm()
|
||||
|
||||
Il metodo confirm() visualizza una finestra di dialogo con un messaggio specificato, insieme a un pulsante OK e uno Cancel.
|
||||
Una finestra di conferma viene spesso utilizzata per chiedere all'utente il permesso di eseguire qualcosa. La finestra confirm() accetta come argomento una stringa.
|
||||
Facendo clic sul pulsante OK si ottiene il valore vero, mentre facendo clic sul pulsante Annulla si ottiene il valore falso.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Questi non sono tutti i metodi delle finestre, ma avremo una sezione separata per approfondire i metodi delle finestre.
|
||||
|
||||
## Oggetto Date
|
||||
|
||||
Il tempo è una cosa importante. Vogliamo conoscere l'ora di una certa attività o evento. In JavaScript l'ora e la data corrente vengono create utilizzando l'oggetto Date di JavaScript. L'oggetto Date fornisce molti metodi per lavorare con la data e l'ora. I metodi che utilizziamo per ottenere informazioni sulla data e sull'ora dai valori di un oggetto Date iniziano con la parola _get_ perché forniscono le informazioni.
|
||||
getFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes, getSeconds(), getMilliseconds(), getTime(), getDay()_
|
||||
|
||||

|
||||
|
||||
### Creare un oggetto data (time)
|
||||
|
||||
Una volta creato l'oggetto time. L'oggetto time fornirà informazioni sul tempo. Creiamo un oggetto time
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now) // Sat Jan 04 2020 00:56:41 GMT+0200 (Eastern European Standard Time)
|
||||
```
|
||||
|
||||
Abbiamo creato un oggetto tempo e possiamo accedere a qualsiasi informazione data e ora dall'oggetto, utilizzando i metodi get che abbiamo menzionato nella tabella.
|
||||
|
||||
### Ottenere Valore Anno
|
||||
|
||||
Estraiamo o otteniamo l'intero anno da un oggetto temporale.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getFullYear()) // 2020
|
||||
```
|
||||
|
||||
### Ottenere Valore mese
|
||||
|
||||
Estraiamo o otteniamo il mese da un oggetto temporale.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getMonth()) // 0, because the month is January, month(0-11)
|
||||
```
|
||||
|
||||
### Ottenere Valore data
|
||||
|
||||
Estraiamo o otteniamo la data del mese da un oggetto temporale.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getDate()) // 4, because the day of the month is 4th, day(1-31)
|
||||
```
|
||||
|
||||
### Ottenere Valore giorno
|
||||
|
||||
Estraiamo o otteniamo il giorno della settimana da un oggetto orario.
|
||||
|
||||
```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)
|
||||
```
|
||||
|
||||
### Ottenere Valore ora
|
||||
|
||||
Estraiamo o otteniamo le ore da un oggetto tempo.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getHours()) // 0, because the time is 00:56:41
|
||||
```
|
||||
|
||||
### Ottenere Valore minuto
|
||||
|
||||
Estraiamo o otteniamo i minuti da un oggetto temporale.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getMinutes()) // 56, because the time is 00:56:41
|
||||
```
|
||||
|
||||
### Ottenere Valore secondo
|
||||
|
||||
Estraiamo o otteniamo i secondi da un oggetto tempo.
|
||||
|
||||
```js
|
||||
const now = new Date()
|
||||
console.log(now.getSeconds()) // 41, because the time is 00:56:41
|
||||
```
|
||||
|
||||
### Ottenere Valore tempo
|
||||
|
||||
Questo metodo fornisce il tempo in millisecondi a partire dal 1° gennaio 1970. È anche noto come tempo Unix. È possibile ottenere l'ora Unix in due modi:
|
||||
|
||||
1. Usare _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. Usare _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
|
||||
```
|
||||
|
||||
Formattiamo questi valori in un formato orario leggibile dall'uomo.
|
||||
**Esempio:**
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
🌕 Hai un'energia sconfinata. Hai appena completato le sfide del terzo giorno e sei a tre passi dalla strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
|
||||
|
||||
## 💻 Day 3: Esercizi
|
||||
|
||||
### Esercizi: Livello 1
|
||||
|
||||
1. Dichiarate le variabili firstName, lastName, country, city, age, isMarried, year e assegnategli un valore; utilizzate l'operatore typeof per verificare i diversi tipi di dati.
|
||||
2. Verificare se il tipo di '10' è uguale a 10.
|
||||
3. Verificare se parseInt('9.8') è uguale a 10
|
||||
4. Il valore booleano è vero o falso.
|
||||
1. Scrivete tre istruzioni JavaScript che forniscano un valore vero.
|
||||
2. Scrivete tre istruzioni JavaScript che forniscono un valore falso.
|
||||
|
||||
5. Scoprite il risultato della seguente espressione di confronto senza usare console.log(). Dopo aver deciso il risultato, confermatelo usando 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. Trovate la lunghezza di pitone e gergo e fate una dichiarazione di confronto falsificata.
|
||||
|
||||
6. Scoprite il risultato delle seguenti espressioni senza usare console.log(). Dopo aver deciso il risultato, confermatelo utilizzando 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. !(falso)
|
||||
8. !(4 > 3 && 10 < 12)
|
||||
9. !(4 > 3 && 10 > 12)
|
||||
10. !(4 === '4')
|
||||
11. Non c'è nessun 'on' sia in dragon che in python.
|
||||
|
||||
7. Utilizzate l'oggetto Date per svolgere le seguenti attività
|
||||
1. Qual è l'anno oggi?
|
||||
2. Qual è il mese di oggi come numero?
|
||||
3. Qual è la data di oggi?
|
||||
4. Qual è il giorno di oggi come numero?
|
||||
5. Qual è l'ora attuale?
|
||||
6. A quanto ammontano i minuti?
|
||||
7. Trovare il numero di secondi trascorsi dal 1° gennaio 1970 a oggi.
|
||||
|
||||
### Esercizi: Livello 2
|
||||
|
||||
1. Scrivere uno script che richieda all'utente di inserire base e altezza del triangolo e di calcolare l'area di un triangolo (area = 0,5 x b x h).
|
||||
|
||||
```sh
|
||||
Inserire base: 20
|
||||
Inserire l'altezza: 10
|
||||
L'area del triangolo è 100
|
||||
```
|
||||
|
||||
1. Scrivete uno script che richieda all'utente di inserire il lato a, il lato b e il lato c del triangolo e che calcoli il perimetro del triangolo (perimetro = a + b + c)
|
||||
|
||||
```sh
|
||||
Inserire il lato a: 5
|
||||
Inserire il lato b: 4
|
||||
Inserire il lato c: 3
|
||||
Il perimetro del triangolo è 12
|
||||
```
|
||||
|
||||
1. Ottenete la lunghezza e la larghezza utilizzando il prompt e calcolate l'area del rettangolo (area = lunghezza x larghezza e il perimetro del rettangolo (perimetro = 2 x (lunghezza + larghezza)).
|
||||
1. Ottenere il raggio utilizzando il prompt e calcolare l'area di un cerchio (area = pi x r x r) e la circonferenza di un cerchio (c = 2 x pi x r) dove 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
|
||||
Il tuo nome, Asabeneh, è più lungo del tuo cognome, Yetayeh
|
||||
```
|
||||
|
||||
1. Dichiarare due variabili _myAge_ e _yourAge_ e assegnare loro i valori iniziali myAge e yourAge.
|
||||
|
||||
```js
|
||||
let myAge = 250
|
||||
let yourAge = 25
|
||||
```
|
||||
|
||||
```sh
|
||||
Ho 225 anni più di te.
|
||||
```
|
||||
|
||||
1. Utilizzando il prompt, ottenete l'anno di nascita dell'utente e se l'utente ha 18 anni o più consentitegli di guidare, altrimenti ditegli di aspettare un certo numero di anni.
|
||||
|
||||
```sh
|
||||
|
||||
Inserire l'anno di nascita: 1995
|
||||
Hai 25 anni. Sei abbastanza grande per guidare
|
||||
|
||||
Inserisci l'anno di nascita: 2005
|
||||
Hai 15 anni. Potrai guidare dopo 3 anni.
|
||||
```
|
||||
|
||||
1. Scrivere uno script che richieda all'utente di inserire il numero di anni. Calcolare il numero di secondi che una persona può vivere. Supponiamo che una persona viva solo cento anni
|
||||
|
||||
```sh
|
||||
Inserisci il numero di anni che vivi: 100
|
||||
Hai vissuto 3153600000 secondi.
|
||||
```
|
||||
|
||||
1. Creare un formato di tempo leggibile dall'uomo utilizzando l'oggetto Date time
|
||||
1. AAAA-MM-GG HH:mm
|
||||
2. GG-MM-AAAA HH:mm
|
||||
3. GG/MM/AAAA HH:mm
|
||||
|
||||
### Esercizi: Livello 3
|
||||
|
||||
1. Creare un formato orario leggibile dall'uomo utilizzando l'oggetto Date time. L'ora e i minuti devono essere sempre a due cifre (7 ore devono essere 07 e 5 minuti devono essere 05).
|
||||
1. YYY-MM-DD HH:mm es. 20120-01-02 07:05
|
||||
|
||||
[<< Day 2](../02_Day_Data_types/02_day_data_types.md) | [Day 4 >>](../04_Day_Conditionals/04_day_conditionals.md)
|
@ -0,0 +1,377 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Condizionali</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 3](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) | [Day 5 >>](../05_Day_Arrays/05_day_arrays.md)
|
||||
|
||||

|
||||
|
||||
- [📔 Giorno 4](#-day-4)
|
||||
- [Condizionali](#conditionals)
|
||||
- [If](#if)
|
||||
- [If Else](#if-else)
|
||||
- [If Else if Else](#if--else-if-else)
|
||||
- [Switch](#switch)
|
||||
- [Operatori Ternari](#ternary-operators)
|
||||
- [💻 Esercizi](#-exercises)
|
||||
- [Esercizi: Livello 1](#exercises-level-1)
|
||||
- [Esercizi: Livello 2](#exercises-level-2)
|
||||
- [Esercizi: Livello 3](#exercises-level-3)
|
||||
|
||||
# 📔 Giorno 4
|
||||
|
||||
## Condizionali
|
||||
|
||||
Le istruzioni condizionali sono utilizzate per prendere decisioni in base a diverse condizioni.
|
||||
Per impostazione predefinita, le istruzioni negli script JavaScript vengono eseguite in sequenza dall'alto verso il basso. Se la logica di elaborazione lo richiede, il flusso sequenziale di esecuzione può essere modificato in due modi:
|
||||
|
||||
- Esecuzione condizionale: un blocco di una o più istruzioni viene eseguito se una certa espressione è vera.
|
||||
- Esecuzione ripetitiva: un blocco di una o più istruzioni verrà eseguito ripetutamente finché una certa espressione sarà vera. In questa sezione tratteremo gli enunciati _if_, _else_, _else if_. Gli operatori di confronto e logici appresi nelle sezioni precedenti saranno utili in questa sede.
|
||||
|
||||
Le condizioni possono essere implementate nei seguenti modi:
|
||||
|
||||
- if
|
||||
- if else
|
||||
- if else if else
|
||||
- switch
|
||||
- ternary operator
|
||||
|
||||
### If
|
||||
|
||||
In JavaScript e in altri linguaggi di programmazione la parola chiave _if_ serve a verificare se una condizione è vera e a eseguire il blocco di codice. Per creare una condizione if, abbiamo bisogno della parola chiave _if_, della condizione all'interno di una parentesi e del blocco di codice all'interno di una parentesi graffa ({}).
|
||||
|
||||
```js
|
||||
// syntax
|
||||
if (condition) {
|
||||
//this part of code runs for truthy condition
|
||||
}
|
||||
```
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
let num = 3
|
||||
if (num > 0) {
|
||||
console.log(`${num} is a positive number`)
|
||||
}
|
||||
// 3 is a positive number
|
||||
```
|
||||
|
||||
Come si può vedere nell'esempio di condizione precedente, 3 è maggiore di 0, quindi è un numero positivo. La condizione era vera e il blocco di codice è stato eseguito. Tuttavia, se la condizione è falsa, non si vedrà alcun risultato.
|
||||
|
||||
```js
|
||||
let isRaining = true
|
||||
if (isRaining) {
|
||||
console.log('Remember to take your rain coat.')
|
||||
}
|
||||
```
|
||||
|
||||
Lo stesso vale per la seconda condizione: se isRaining è false, il blocco if non verrà eseguito e non vedremo alcun output. Per vedere il risultato di una condizione falsa, dovremmo avere un altro blocco, che sarà _else_.
|
||||
|
||||
### If Else
|
||||
|
||||
Se la condizione è vera, viene eseguito il primo blocco, altrimenti viene eseguita la condizione else.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
if (condition) {
|
||||
// this part of code runs for truthy condition
|
||||
} else {
|
||||
// this part of code runs for false condition
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
let num = 3
|
||||
if (num > 0) {
|
||||
console.log(`${num} is a positive number`)
|
||||
} else {
|
||||
console.log(`${num} is a negative number`)
|
||||
}
|
||||
// 3 is a positive number
|
||||
|
||||
num = -3
|
||||
if (num > 0) {
|
||||
console.log(`${num} is a positive number`)
|
||||
} else {
|
||||
console.log(`${num} is a negative number`)
|
||||
}
|
||||
// -3 is a negative number
|
||||
```
|
||||
|
||||
```js
|
||||
let isRaining = true
|
||||
if (isRaining) {
|
||||
console.log('You need a rain coat.')
|
||||
} else {
|
||||
console.log('No need for a rain coat.')
|
||||
}
|
||||
// You need a rain coat.
|
||||
|
||||
isRaining = false
|
||||
if (isRaining) {
|
||||
console.log('You need a rain coat.')
|
||||
} else {
|
||||
console.log('No need for a rain coat.')
|
||||
}
|
||||
// No need for a rain coat.
|
||||
```
|
||||
|
||||
L'ultima condizione è falsa, quindi il blocco else è stato eseguito. Cosa succede se abbiamo più di due condizioni? In questo caso, utilizzeremo le condizioni *else if*.
|
||||
|
||||
### If Else if Else
|
||||
|
||||
Nella nostra vita quotidiana prendiamo decisioni su base giornaliera. Le decisioni non vengono prese verificando una o due condizioni, ma sulla base di più condizioni. Come la nostra vita quotidiana, anche la programmazione è piena di condizioni. Usiamo *else if* quando abbiamo più condizioni.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
if (condition) {
|
||||
// code
|
||||
} else if (condition) {
|
||||
// code
|
||||
} else {
|
||||
// code
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
let a = 0
|
||||
if (a > 0) {
|
||||
console.log(`${a} is a positive number`)
|
||||
} else if (a < 0) {
|
||||
console.log(`${a} is a negative number`)
|
||||
} else if (a == 0) {
|
||||
console.log(`${a} is zero`)
|
||||
} else {
|
||||
console.log(`${a} is not a number`)
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// if else if else
|
||||
let weather = 'sunny'
|
||||
if (weather === 'rainy') {
|
||||
console.log('You need a rain coat.')
|
||||
} else if (weather === 'cloudy') {
|
||||
console.log('It might be cold, you need a jacket.')
|
||||
} else if (weather === 'sunny') {
|
||||
console.log('Go out freely.')
|
||||
} else {
|
||||
console.log('No need for rain coat.')
|
||||
}
|
||||
```
|
||||
|
||||
### Switch
|
||||
|
||||
Switch è un'alternativa a **if else if else**.
|
||||
L'istruzione switch inizia con la parola chiave *switch* seguita da una parentesi e da un blocco di codice. All'interno del blocco di codice avremo diversi casi. Il blocco Case viene eseguito se il valore nella parentesi dell'istruzione switch corrisponde al valore del caso. L'istruzione break serve a terminare l'esecuzione, in modo che l'esecuzione del codice non venga interrotta dopo che la condizione è stata soddisfatta. Il blocco default viene eseguito se tutti i casi non soddisfano la condizione.
|
||||
|
||||
```js
|
||||
switch(caseValue){
|
||||
case 1:
|
||||
// code
|
||||
break
|
||||
case 2:
|
||||
// code
|
||||
break
|
||||
case 3:
|
||||
// code
|
||||
break
|
||||
default:
|
||||
// code
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
let weather = 'cloudy'
|
||||
switch (weather) {
|
||||
case 'rainy':
|
||||
console.log('You need a rain coat.')
|
||||
break
|
||||
case 'cloudy':
|
||||
console.log('It might be cold, you need a jacket.')
|
||||
break
|
||||
case 'sunny':
|
||||
console.log('Go out freely.')
|
||||
break
|
||||
default:
|
||||
console.log(' No need for rain coat.')
|
||||
}
|
||||
|
||||
// Switch More Examples
|
||||
let dayUserInput = prompt('What day is today ?')
|
||||
let day = dayUserInput.toLowerCase()
|
||||
|
||||
switch (day) {
|
||||
case 'monday':
|
||||
console.log('Today is Monday')
|
||||
break
|
||||
case 'tuesday':
|
||||
console.log('Today is Tuesday')
|
||||
break
|
||||
case 'wednesday':
|
||||
console.log('Today is Wednesday')
|
||||
break
|
||||
case 'thursday':
|
||||
console.log('Today is Thursday')
|
||||
break
|
||||
case 'friday':
|
||||
console.log('Today is Friday')
|
||||
break
|
||||
case 'saturday':
|
||||
console.log('Today is Saturday')
|
||||
break
|
||||
case 'sunday':
|
||||
console.log('Today is Sunday')
|
||||
break
|
||||
default:
|
||||
console.log('It is not a week day.')
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
// Esempi di utilizzo delle condizioni nei casi
|
||||
|
||||
```js
|
||||
let num = prompt('Enter number');
|
||||
switch (true) {
|
||||
case num > 0:
|
||||
console.log('Number is positive');
|
||||
break;
|
||||
case num == 0:
|
||||
console.log('Numbers is zero');
|
||||
break;
|
||||
case num < 0:
|
||||
console.log('Number is negative');
|
||||
break;
|
||||
default:
|
||||
console.log('Entered value was not a number');
|
||||
}
|
||||
```
|
||||
|
||||
### Operatori Ternari
|
||||
|
||||
Un altro modo di scrivere i condizionali è quello di utilizzare gli operatori ternari. Ne abbiamo parlato in altre sezioni, ma è bene menzionarlo anche qui.
|
||||
|
||||
```js
|
||||
let isRaining = true
|
||||
isRaining
|
||||
? console.log('You need a rain coat.')
|
||||
: console.log('No need for a rain coat.')
|
||||
```
|
||||
|
||||
🌕 sei straordinario e hai un potenziale notevole. Hai appena completato le sfide del quarto giorno e sei quattro passi avanti sulla strada della grandezza. Ora fai qualche esercizio per il cervello e i muscoli.
|
||||
|
||||
## 💻 Esercizi
|
||||
|
||||
### Esercizi: Livello 1
|
||||
|
||||
1. Ottenere l'input dell'utente tramite prompt("Inserisci la tua età:"). Se l'utente ha 18 anni o più, fornisce il feedback: "Sei abbastanza grande per guidare", ma se non ha 18 anni, fornisce un altro feedback che indica di aspettare il numero di anni necessari per compierli.
|
||||
|
||||
```sh
|
||||
Inserisci la tua età: 30
|
||||
Sei abbastanza grande per guidare.
|
||||
|
||||
Inserisci la tua età: 15
|
||||
Ti restano 3 anni per guidare.
|
||||
```
|
||||
|
||||
1. Confrontare i valori di myAge e yourAge usando if ... else. Basarsi sul confronto e registrare il risultato nella console, indicando chi è più vecchio (io o tu). Utilizzare prompt("Inserisci la tua età:") per ottenere l'età come input.
|
||||
|
||||
```sh
|
||||
Inserisci la tua età: 30
|
||||
Sei più vecchio di me di 5 anni.
|
||||
```
|
||||
|
||||
1. Se a è maggiore di b restituisce 'a è maggiore di b' altrimenti 'a è minore di b'. Provate a implementarlo in diversi modi
|
||||
|
||||
- usando if else
|
||||
- l'operatore ternario.
|
||||
|
||||
```js
|
||||
lasciare a = 4
|
||||
lasciare che b = 3
|
||||
```
|
||||
|
||||
``sh
|
||||
4 è maggiore di 3
|
||||
```
|
||||
|
||||
1. I numeri pari sono divisibili per 2 e il resto è zero. Come si fa a verificare se un numero è pari o no usando JavaScript?
|
||||
|
||||
```sh
|
||||
Inserite un numero: 2
|
||||
2 è un numero pari
|
||||
|
||||
Inserite un numero: 9
|
||||
9 è un numero dispari.
|
||||
```
|
||||
|
||||
### Esercizi: Livello 2
|
||||
|
||||
1. Scrivere un codice in grado di dare voti agli studenti in base ai loro punteggi:
|
||||
- 80-100, A
|
||||
- 70-89, B
|
||||
- 60-69, C
|
||||
- 50-59, D
|
||||
- 0-49, F
|
||||
1. Controllare se la stagione è autunno, inverno, primavera o estate.
|
||||
Se l'input dell'utente è :
|
||||
- Settembre, Ottobre o Novembre, la stagione è Autunno.
|
||||
- Dicembre, gennaio o febbraio, la stagione è Inverno.
|
||||
- Marzo, aprile o maggio, la stagione è la primavera.
|
||||
- Giugno, luglio o agosto, la stagione è l'estate.
|
||||
1. Controllare se un giorno è un giorno del fine settimana o un giorno lavorativo. Il vostro script prenderà il giorno come input.
|
||||
|
||||
```sh
|
||||
Che giorno è oggi? Sabato
|
||||
Sabato è un fine settimana.
|
||||
|
||||
Che giorno è oggi? sabato
|
||||
Sabato è un fine settimana.
|
||||
|
||||
Che giorno è oggi? venerdì
|
||||
Venerdì è un giorno lavorativo.
|
||||
|
||||
Che giorno è oggi? venerdì
|
||||
Venerdì è un giorno lavorativo.
|
||||
```
|
||||
|
||||
### Esercizi: Livello 3
|
||||
|
||||
1. Scrivere un programma che indichi il numero di giorni in un mese.
|
||||
|
||||
```sh
|
||||
Inserire un mese: Gennaio
|
||||
Gennaio ha 31 giorni.
|
||||
|
||||
Inserire un mese: GENNAIO
|
||||
Gennaio ha 31 giorni
|
||||
|
||||
Inserire un mese: Febbraio
|
||||
Febbraio ha 28 giorni.
|
||||
|
||||
Inserire un mese: FEBBRAIO
|
||||
Febbraio ha 28 giorni.
|
||||
```
|
||||
|
||||
1. Scrivere un programma che indichi il numero di giorni in un mese, considerando l'anno bisestile.
|
||||
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 3](../03_Day_Booleans_operators_date/03_booleans_operators_date.md) | [Day 5 >>](../05_Day_Arrays/05_day_arrays.md)
|
@ -0,0 +1,774 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Arrays</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 4](../04_Day_Conditionals/04_day_conditionals.md) | [Day 6 >>](../06_Day_Loops/06_day_loops.md)
|
||||
|
||||

|
||||
|
||||
- [📔 Giorno 5](#-day-5)
|
||||
- [Arrays](#arrays)
|
||||
- [Come creare un array vuoto](#how-to-create-an-empty-array)
|
||||
- [Come creare un array contenente valori](#how-to-create-an-array-with-values)
|
||||
- [Creare un array usando la funzione split](#creating-an-array-using-split)
|
||||
- [Accedere agli elementi dell'array usando l'indice](#accessing-array-items-using-index)
|
||||
- [Modificare gli elementi dell'array](#modifying-array-element)
|
||||
- [Metodi per manipolare gli array](#methods-to-manipulate-array)
|
||||
- [Il Costruttore dell'array](#array-constructor)
|
||||
- [Creare valori statici con fill](#creating-static-values-with-fill)
|
||||
- [Concatenare array usando concat](#concatenating-array-using-concat)
|
||||
- [Ottenere la lunghezza dell'array](#getting-array-length)
|
||||
- [Ottenere l'indice di un elemento nell'array](#getting-index-an-element-in-arr-array)
|
||||
- [Ottenere l'ultimo indice di un elemento nell'array](#getting-last-index-of-an-element-in-array)
|
||||
- [Verificare l'array](#checking-array)
|
||||
- [Convertire l'array in stringa](#converting-array-to-string)
|
||||
- [Unire elementi array](#joining-array-elements)
|
||||
- [Dividere gli elementi dell'array](#slice-array-elements)
|
||||
- [Il metodo Splice con gli array](#splice-method-in-array)
|
||||
- [Aggiungere un elemento all'array usando push](#adding-item-to-an-array-using-push)
|
||||
- [Rimuovere l'ultimo elemento usando pop](#removing-the-end-element-using-pop)
|
||||
- [Rimuovere un elemento dall'inizio dell'array](#removing-an-element-from-the-beginning)
|
||||
- [Aggiungere un elemento in prima posizione dell'array](#add-an-element-from-the-beginning)
|
||||
- [Invertire l'ordine dell'array](#reversing-array-order)
|
||||
- [Ordinare gli elementi di un array](#sorting-elements-in-array)
|
||||
- [Array di array](#array-of-arrays)
|
||||
- [💻 Esercizio](#-exercise)
|
||||
- [Esercizio: Livello 1](#exercise-level-1)
|
||||
- [Esercizio: Livello 2](#exercise-level-2)
|
||||
- [Esercizio: Livello 3](#exercise-level-3)
|
||||
|
||||
# 📔 Giorno 5
|
||||
|
||||
## Arrays
|
||||
|
||||
A differenza delle variabili, un array può memorizzare _molti valori_. Ogni valore in un array ha un _indice_ e ogni indice ha _un riferimento in un indirizzo di memoria_. È possibile accedere a ciascun valore utilizzando i loro _indici_. L'indice di un array parte da _zero_ e l'indice dell'ultimo elemento è diminuito di uno rispetto alla lunghezza dell'array.
|
||||
|
||||
Un array è una raccolta di diversi tipi di dati ordinati e modificabili. Un array consente di memorizzare elementi duplicati e tipi di dati diversi. Una array può essere vuoto o può contenere valori di tipi di dati diversi.
|
||||
|
||||
### Come creare un array vuoto
|
||||
|
||||
In JavaScript, possiamo creare un array in diversi modi. Vediamo i diversi modi per creare un array.
|
||||
È molto comune usare _const_ invece di _let_ per dichiarare una variabile di un array. Se si usa const, significa che non si usa più il nome di quella variabile.
|
||||
|
||||
- Usare il costruttore Array
|
||||
|
||||
```js
|
||||
// syntax
|
||||
const arr = Array()
|
||||
// or
|
||||
// let arr = new Array()
|
||||
console.log(arr) // []
|
||||
```
|
||||
|
||||
- Usare le parentesi quadre ([])
|
||||
|
||||
```js
|
||||
// syntax
|
||||
// This the most recommended way to create an empty list
|
||||
const arr = []
|
||||
console.log(arr)
|
||||
```
|
||||
|
||||
### Come creare un array contenente valori
|
||||
|
||||
Array con valori iniziali. Utilizziamo la proprietà _length_ per trovare la lunghezza di un array.
|
||||
|
||||
```js
|
||||
const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // array of numbers
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of strings, fruits
|
||||
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of strings, vegetables
|
||||
const animalProducts = ['milk', 'meat', 'butter', 'yoghurt'] // array of strings, products
|
||||
const webTechs = ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] // array of web technologies
|
||||
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland'] // array of strings, countries
|
||||
|
||||
// Print the array and its length
|
||||
|
||||
console.log('Numbers:', numbers)
|
||||
console.log('Number of numbers:', numbers.length)
|
||||
|
||||
console.log('Fruits:', fruits)
|
||||
console.log('Number of fruits:', fruits.length)
|
||||
|
||||
console.log('Vegetables:', vegetables)
|
||||
console.log('Number of vegetables:', vegetables.length)
|
||||
|
||||
console.log('Animal products:', animalProducts)
|
||||
console.log('Number of animal products:', animalProducts.length)
|
||||
|
||||
console.log('Web technologies:', webTechs)
|
||||
console.log('Number of web technologies:', webTechs.length)
|
||||
|
||||
console.log('Countries:', countries)
|
||||
console.log('Number of countries:', countries.length)
|
||||
```
|
||||
|
||||
```sh
|
||||
Numbers: [0, 3.14, 9.81, 37, 98.6, 100]
|
||||
Number of numbers: 6
|
||||
Fruits: ['banana', 'orange', 'mango', 'lemon']
|
||||
Number of fruits: 4
|
||||
Vegetables: ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
|
||||
Number of vegetables: 5
|
||||
Animal products: ['milk', 'meat', 'butter', 'yoghurt']
|
||||
Number of animal products: 4
|
||||
Web technologies: ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB']
|
||||
Number of web technologies: 7
|
||||
Countries: ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway']
|
||||
Number of countries: 5
|
||||
```
|
||||
|
||||
- Un array può contenere elementi di diversi tipi di dati
|
||||
|
||||
```js
|
||||
const arr = [
|
||||
'Asabeneh',
|
||||
250,
|
||||
true,
|
||||
{ country: 'Finland', city: 'Helsinki' },
|
||||
{ skills: ['HTML', 'CSS', 'JS', 'React', 'Python'] }
|
||||
] // arr containing different data types
|
||||
console.log(arr)
|
||||
```
|
||||
|
||||
### Creare un array usando la funzione split
|
||||
|
||||
Come abbiamo visto nella sezione precedente, possiamo dividere una stringa in diverse posizioni e convertirla in un array. Vediamo gli esempi seguenti.
|
||||
|
||||
```js
|
||||
let js = 'JavaScript'
|
||||
const charsInJavaScript = js.split('')
|
||||
|
||||
console.log(charsInJavaScript) // ["J", "a", "v", "a", "S", "c", "r", "i", "p", "t"]
|
||||
|
||||
let companiesString = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon'
|
||||
const companies = companiesString.split(',')
|
||||
|
||||
console.log(companies) // ["Facebook", " Google", " Microsoft", " Apple", " IBM", " Oracle", " Amazon"]
|
||||
let txt =
|
||||
'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
|
||||
const words = txt.split(' ')
|
||||
|
||||
console.log(words)
|
||||
// the text has special characters think how you can just get only the words
|
||||
// ["I", "love", "teaching", "and", "empowering", "people.", "I", "teach", "HTML,", "CSS,", "JS,", "React,", "Python"]
|
||||
```
|
||||
|
||||
### Accedere agli elementi dell'array usando l'indice
|
||||
|
||||
Si accede a ciascun elemento di un array utilizzando il suo indice. L'indice di un array parte da 0. L'immagine seguente mostra chiaramente l'indice di ciascun elemento dell'array.
|
||||
|
||||

|
||||
|
||||
```js
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon']
|
||||
let firstFruit = fruits[0] // we are accessing the first item using its index
|
||||
|
||||
console.log(firstFruit) // banana
|
||||
|
||||
secondFruit = fruits[1]
|
||||
console.log(secondFruit) // orange
|
||||
|
||||
let lastFruit = fruits[3]
|
||||
console.log(lastFruit) // lemon
|
||||
// Last index can be calculated as follows
|
||||
|
||||
let lastIndex = fruits.length - 1
|
||||
lastFruit = fruits[lastIndex]
|
||||
|
||||
console.log(lastFruit) // lemon
|
||||
```
|
||||
|
||||
```js
|
||||
const numbers = [0, 3.14, 9.81, 37, 98.6, 100] // set of numbers
|
||||
|
||||
console.log(numbers.length) // => to know the size of the array, which is 6
|
||||
console.log(numbers) // -> [0, 3.14, 9.81, 37, 98.6, 100]
|
||||
console.log(numbers[0]) // -> 0
|
||||
console.log(numbers[5]) // -> 100
|
||||
|
||||
let lastIndex = numbers.length - 1;
|
||||
console.log(numbers[lastIndex]) // -> 100
|
||||
```
|
||||
|
||||
```js
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
] // List of web technologies
|
||||
|
||||
console.log(webTechs) // all the array items
|
||||
console.log(webTechs.length) // => to know the size of the array, which is 7
|
||||
console.log(webTechs[0]) // -> HTML
|
||||
console.log(webTechs[6]) // -> MongoDB
|
||||
|
||||
let lastIndex = webTechs.length - 1
|
||||
console.log(webTechs[lastIndex]) // -> MongoDB
|
||||
```
|
||||
|
||||
```js
|
||||
const countries = [
|
||||
'Albania',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya'
|
||||
] // List of countries
|
||||
|
||||
console.log(countries) // -> all countries in array
|
||||
console.log(countries[0]) // -> Albania
|
||||
console.log(countries[10]) // -> Kenya
|
||||
|
||||
let lastIndex = countries.length - 1;
|
||||
console.log(countries[lastIndex]) // -> Kenya
|
||||
```
|
||||
|
||||
```js
|
||||
const shoppingCart = [
|
||||
'Milk',
|
||||
'Mango',
|
||||
'Tomato',
|
||||
'Potato',
|
||||
'Avocado',
|
||||
'Meat',
|
||||
'Eggs',
|
||||
'Sugar'
|
||||
] // List of food products
|
||||
|
||||
console.log(shoppingCart) // -> all shoppingCart in array
|
||||
console.log(shoppingCart[0]) // -> Milk
|
||||
console.log(shoppingCart[7]) // -> Sugar
|
||||
|
||||
let lastIndex = shoppingCart.length - 1;
|
||||
console.log(shoppingCart[lastIndex]) // -> Sugar
|
||||
```
|
||||
|
||||
### Modificare gli elementi dell'array
|
||||
|
||||
Un array è mutabile (modificabile). Una volta creato un array, è possibile modificarne il contenuto degli elementi.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers[0] = 10 // changing 1 at index 0 to 10
|
||||
numbers[1] = 20 // changing 2 at index 1 to 20
|
||||
|
||||
console.log(numbers) // [10, 20, 3, 4, 5]
|
||||
|
||||
const countries = [
|
||||
'Albania',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya'
|
||||
]
|
||||
|
||||
countries[0] = 'Afghanistan' // Replacing Albania by Afghanistan
|
||||
let lastIndex = countries.length - 1
|
||||
countries[lastIndex] = 'Korea' // Replacing Kenya by Korea
|
||||
|
||||
console.log(countries)
|
||||
```
|
||||
|
||||
```sh
|
||||
["Afghanistan", "Bolivia", "Canada", "Denmark", "Ethiopia", "Finland", "Germany", "Hungary", "Ireland", "Japan", "Korea"]
|
||||
```
|
||||
|
||||
### Methods to manipulate array
|
||||
|
||||
Esistono diversi metodi per manipolare un array. Questi sono alcuni dei metodi disponibili per gestire gli array:_Array, length, concat, indexOf, slice, splice, join, toString, includes, lastIndexOf, isArray, fill, push, pop, shift, unshift_
|
||||
|
||||
#### Il Costruttore dell'array
|
||||
|
||||
Array: Crea un array.
|
||||
|
||||
```js
|
||||
const arr = Array() // creates an an empty array
|
||||
console.log(arr)
|
||||
|
||||
const eightEmptyValues = Array(8) // it creates eight empty values
|
||||
console.log(eightEmptyValues) // [empty x 8]
|
||||
```
|
||||
|
||||
#### Creare valori statici con fill
|
||||
|
||||
fill: Riempe l'array con l'elemento specificato.
|
||||
|
||||
```js
|
||||
const arr = Array() // creates an an empty array
|
||||
console.log(arr)
|
||||
|
||||
const eightXvalues = Array(8).fill('X') // it creates eight element values filled with 'X'
|
||||
console.log(eightXvalues) // ['X', 'X','X','X','X','X','X','X']
|
||||
|
||||
const eight0values = Array(8).fill(0) // it creates eight element values filled with '0'
|
||||
console.log(eight0values) // [0, 0, 0, 0, 0, 0, 0, 0]
|
||||
|
||||
const four4values = Array(4).fill(4) // it creates 4 element values filled with '4'
|
||||
console.log(four4values) // [4, 4, 4, 4]
|
||||
```
|
||||
|
||||
#### Concatenare array usando concat
|
||||
|
||||
concat: Concatena due array.
|
||||
|
||||
```js
|
||||
const firstList = [1, 2, 3]
|
||||
const secondList = [4, 5, 6]
|
||||
const thirdList = firstList.concat(secondList)
|
||||
|
||||
console.log(thirdList) // [1, 2, 3, 4, 5, 6]
|
||||
```
|
||||
|
||||
```js
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon'] // array of fruits
|
||||
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] // array of vegetables
|
||||
const fruitsAndVegetables = fruits.concat(vegetables) // concatenate the two arrays
|
||||
|
||||
console.log(fruitsAndVegetables)
|
||||
```
|
||||
|
||||
```sh
|
||||
["banana", "orange", "mango", "lemon", "Tomato", "Potato", "Cabbage", "Onion", "Carrot"]
|
||||
```
|
||||
|
||||
#### Ottenere la lunghezza dell'array
|
||||
|
||||
Length:Per conoscere la lunghezza dell'array.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
console.log(numbers.length) // -> 5 is the size of the array
|
||||
```
|
||||
|
||||
#### Ottenere l'indice di un elemento nell'array
|
||||
|
||||
indexOf:Per verificare se un elemento esiste in un array. Se esiste, viene restituito l'indice, altrimenti viene restituito -1.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
console.log(numbers.indexOf(5)) // -> 4
|
||||
console.log(numbers.indexOf(0)) // -> -1
|
||||
console.log(numbers.indexOf(1)) // -> 0
|
||||
console.log(numbers.indexOf(6)) // -> -1
|
||||
```
|
||||
|
||||
Controlla che l'elemento esista nell'array.
|
||||
|
||||
- Controlla gli elementi in una lista.
|
||||
|
||||
```js
|
||||
// let us check if a banana exist in the array
|
||||
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon']
|
||||
let index = fruits.indexOf('banana') // 0
|
||||
|
||||
if(index === -1){
|
||||
console.log('This fruit does not exist in the array')
|
||||
} else {
|
||||
console.log('This fruit does exist in the array')
|
||||
}
|
||||
// This fruit does exist in the array
|
||||
|
||||
// we can use also ternary here
|
||||
index === -1 ? console.log('This fruit does not exist in the array'): console.log('This fruit does exist in the array')
|
||||
|
||||
// let us check if an avocado exist in the array
|
||||
let indexOfAvocado = fruits.indexOf('avocado') // -1, if the element not found index is -1
|
||||
if(indexOfAvocado === -1){
|
||||
console.log('This fruit does not exist in the array')
|
||||
} else {
|
||||
console.log('This fruit does exist in the array')
|
||||
}
|
||||
// This fruit does not exist in the array
|
||||
```
|
||||
|
||||
#### Ottenere l'ultimo indice di un elemento nell'array
|
||||
|
||||
lastIndexOf: Fornisce la posizione dell'ultimo elemento dell'array. Se esiste, restituisce l'indice, altrimenti restituisce -1.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5, 3, 1, 2]
|
||||
|
||||
console.log(numbers.lastIndexOf(2)) // 7
|
||||
console.log(numbers.lastIndexOf(0)) // -1
|
||||
console.log(numbers.lastIndexOf(1)) // 6
|
||||
console.log(numbers.lastIndexOf(4)) // 3
|
||||
console.log(numbers.lastIndexOf(6)) // -1
|
||||
```
|
||||
|
||||
includes:Per verificare se un elemento esiste in un array. Se esiste, restituisce true, altrimenti restituisce false.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
console.log(numbers.includes(5)) // true
|
||||
console.log(numbers.includes(0)) // false
|
||||
console.log(numbers.includes(1)) // true
|
||||
console.log(numbers.includes(6)) // false
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
] // List of web technologies
|
||||
|
||||
console.log(webTechs.includes('Node')) // true
|
||||
console.log(webTechs.includes('C')) // false
|
||||
```
|
||||
|
||||
#### Verificare l'array
|
||||
|
||||
Array.isArray:Per verificare se il tipo di dato è un array.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
console.log(Array.isArray(numbers)) // true
|
||||
|
||||
const number = 100
|
||||
console.log(Array.isArray(number)) // false
|
||||
```
|
||||
|
||||
#### Convertire l'array in stringa
|
||||
|
||||
toString:Converts array to string
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
console.log(numbers.toString()) // 1,2,3,4,5
|
||||
|
||||
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
|
||||
console.log(names.toString()) // Asabeneh,Mathias,Elias,Brook
|
||||
```
|
||||
|
||||
#### Unire elementi array
|
||||
|
||||
join: Viene utilizzato per unire gli elementi dell'array; l'argomento passato nel metodo join verrà unito con l'array e restituito come stringa. Per impostazione predefinita, unisce con una virgola, ma possiamo passare diversi parametri stringa che possono unire gli elementi.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
console.log(numbers.join()) // 1,2,3,4,5
|
||||
|
||||
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
|
||||
|
||||
console.log(names.join()) // Asabeneh,Mathias,Elias,Brook
|
||||
console.log(names.join('')) //AsabenehMathiasEliasBrook
|
||||
console.log(names.join(' ')) //Asabeneh Mathias Elias Brook
|
||||
console.log(names.join(', ')) //Asabeneh, Mathias, Elias, Brook
|
||||
console.log(names.join(' # ')) //Asabeneh # Mathias # Elias # Brook
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
] // List of web technologies
|
||||
|
||||
console.log(webTechs.join()) // "HTML,CSS,JavaScript,React,Redux,Node,MongoDB"
|
||||
console.log(webTechs.join(' # ')) // "HTML # CSS # JavaScript # React # Redux # Node # MongoDB"
|
||||
```
|
||||
|
||||
#### Dividere gli elementi dell'array
|
||||
|
||||
Slice: Per ritagliare più elementi in un intervallo. Richiede due parametri: posizione iniziale e posizione finale. Non include la posizione finale.
|
||||
|
||||
```js
|
||||
const numbers = [1,2,3,4,5]
|
||||
|
||||
console.log(numbers.slice()) // -> it copies all item
|
||||
console.log(numbers.slice(0)) // -> it copies all item
|
||||
console.log(numbers.slice(0, numbers.length)) // it copies all item
|
||||
console.log(numbers.slice(1,4)) // -> [2,3,4] // it doesn't include the ending position
|
||||
```
|
||||
|
||||
#### Il metodo Splice con gli array
|
||||
|
||||
Splice: Richiede tre parametri: posizione iniziale, numero di volte da rimuovere e numero di elementi da aggiungere.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.splice()
|
||||
console.log(numbers) // -> remove all items
|
||||
|
||||
```
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.splice(0,1)
|
||||
console.log(numbers) // remove the first item
|
||||
```
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5, 6]
|
||||
numbers.splice(3, 3, 7, 8, 9)
|
||||
console.log(numbers.splice(3, 3, 7, 8, 9)) // -> [1, 2, 3, 7, 8, 9] //it removes three item and replace three items
|
||||
```
|
||||
|
||||
#### Aggiungere un elemento all'array usando push
|
||||
|
||||
Push: Per aggiungere un elemento alla fine di un array esistente, si usa il metodo push.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
const arr = ['item1', 'item2','item3']
|
||||
arr.push('new item')
|
||||
console.log(arr)
|
||||
// ['item1', 'item2','item3','new item']
|
||||
```
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.push(6)
|
||||
console.log(numbers) // -> [1,2,3,4,5,6]
|
||||
|
||||
numbers.pop() // -> remove one item from the end
|
||||
console.log(numbers) // -> [1,2,3,4,5]
|
||||
```
|
||||
|
||||
```js
|
||||
let fruits = ['banana', 'orange', 'mango', 'lemon']
|
||||
fruits.push('apple')
|
||||
console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple']
|
||||
|
||||
fruits.push('lime')
|
||||
console.log(fruits) // ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime']
|
||||
```
|
||||
|
||||
#### Rimuovere l'ultimo elemento usando pop
|
||||
|
||||
pop: Rimuove l' elemento in coda.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.pop() // -> remove one item from the end
|
||||
console.log(numbers) // -> [1,2,3,4]
|
||||
```
|
||||
|
||||
#### Rimuovere un elemento dall'inizio dell'array
|
||||
|
||||
shift: Rimuove l'elemento in testa (prima posizione).
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.shift() // -> remove one item from the beginning
|
||||
console.log(numbers) // -> [2,3,4,5]
|
||||
```
|
||||
|
||||
#### Aggiungere un elemento in prima posizione dell'array
|
||||
|
||||
unshift: Aggiunge un elemento in prima posizione.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.unshift(0) // -> add one item from the beginning
|
||||
console.log(numbers) // -> [0,1,2,3,4,5]
|
||||
```
|
||||
|
||||
#### Invertire l'ordine dell'array
|
||||
|
||||
reverse: Inverti l'ordine degli elementi.
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
numbers.reverse() // -> reverse array order
|
||||
console.log(numbers) // [5, 4, 3, 2, 1]
|
||||
|
||||
numbers.reverse()
|
||||
console.log(numbers) // [1, 2, 3, 4, 5]
|
||||
```
|
||||
|
||||
#### Ordinare gli elementi di un array
|
||||
|
||||
sort: dispone gli elementi dell'array in ordine crescente. L'ordinamento richiede una funzione di richiamo; vedremo come utilizzare l'ordinamento con una funzione di richiamo nelle prossime sezioni.
|
||||
|
||||
```js
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
]
|
||||
|
||||
webTechs.sort()
|
||||
console.log(webTechs) // ["CSS", "HTML", "JavaScript", "MongoDB", "Node", "React", "Redux"]
|
||||
|
||||
webTechs.reverse() // after sorting we can reverse it
|
||||
console.log(webTechs) // ["Redux", "React", "Node", "MongoDB", "JavaScript", "HTML", "CSS"]
|
||||
```
|
||||
|
||||
### Array di array
|
||||
|
||||
Gli array possono memorizzare diversi tipi di dati, compreso l'array stesso. Creiamo un array di array
|
||||
|
||||
```js
|
||||
const firstNums = [1, 2, 3]
|
||||
const secondNums = [1, 4, 9]
|
||||
|
||||
const arrayOfArray = [[1, 2, 3], [1, 2, 3]]
|
||||
console.log(arrayOfArray[0]) // [1, 2, 3]
|
||||
|
||||
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
|
||||
const backEnd = ['Node','Express', 'MongoDB']
|
||||
const fullStack = [frontEnd, backEnd]
|
||||
console.log(fullStack) // [["HTML", "CSS", "JS", "React", "Redux"], ["Node", "Express", "MongoDB"]]
|
||||
console.log(fullStack.length) // 2
|
||||
console.log(fullStack[0]) // ["HTML", "CSS", "JS", "React", "Redux"]
|
||||
console.log(fullStack[1]) // ["Node", "Express", "MongoDB"]
|
||||
```
|
||||
|
||||
🌕 Sei diligenti e hai già ottenuto molti risultati. Hai appena completato le sfide del 5° giorno e sei a 5 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
|
||||
|
||||
## 💻 Esercizio
|
||||
|
||||
### Esercizio: Livello 1
|
||||
|
||||
```js
|
||||
const countries = [
|
||||
'Albania',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya'
|
||||
]
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
]
|
||||
```
|
||||
|
||||
1. Dichiarare un array _vuoto_;
|
||||
2. Dichiarare un array con un numero di elementi superiore a 5
|
||||
3. Trovare la lunghezza dell'array
|
||||
4. Ottenere il primo elemento, l'elemento centrale e l'ultimo elemento dell'array.
|
||||
5. Dichiarare un array chiamato _mixedDataTypes_, inserire diversi tipi di dati nell'array e trovare la lunghezza dell'array. La dimensione dell'array deve essere maggiore di 5
|
||||
6. Dichiarare una variabile array chiamata itAziende e assegnare i valori iniziali Facebook, Google, Microsoft, Apple, IBM, Oracle e Amazon.
|
||||
7. Stampare l'array utilizzando _console.log()_.
|
||||
8. Stampare il numero di aziende nell'array
|
||||
9. Stampare la prima azienda, la metà e l'ultima azienda
|
||||
10. Stampare ogni azienda
|
||||
11. Cambiare il nome di ogni azienda in maiuscolo, uno per uno, e stamparli.
|
||||
12. Stampare la matrice come una frase: Facebook, Google, Microsoft, Apple, IBM, Oracle e Amazon sono grandi aziende IT.
|
||||
13. Controllare se una certa azienda esiste nell'array itCompanies. Se esiste, restituisce l'azienda, altrimenti restituisce un'azienda _non trovata_.
|
||||
14. Filtrare le aziende che hanno più di una "o" senza il metodo del filtro.
|
||||
15. Ordinare l'array usando il metodo _sort()_.
|
||||
16. Invertire l'array utilizzando il metodo _reverse()_.
|
||||
17. Estrarre le prime 3 società dall'array.
|
||||
18. Eliminare le ultime 3 aziende dall'array.
|
||||
19. Eliminare dall'array l'azienda o le aziende IT centrali.
|
||||
20. Rimuovere la prima azienda IT dall'array
|
||||
21. Rimuovere l'azienda o le aziende IT centrali dall'array.
|
||||
22. Rimuovere l'ultima azienda IT dall'array
|
||||
23. Rimuovere tutte le aziende IT
|
||||
|
||||
### Esercizio: Livello 2
|
||||
|
||||
1. Creare un file separato countries.js e memorizzare l'array dei Paesi in questo file, creare un file separato web_techs.js e memorizzare l'array webTechs in questo file. Accedere a entrambi i file nel file main.js
|
||||
1. Per prima cosa rimuovete tutte le punteggiature, cambiate la stringa in array e contate il numero di parole nell'array.
|
||||
|
||||
```js
|
||||
let text =
|
||||
'I love teaching and empowering people. I teach HTML, CSS, JS, React, Python.'
|
||||
console.log(words)
|
||||
console.log(words.length)
|
||||
```
|
||||
|
||||
```sh
|
||||
["I", "love", "teaching", "and", "empowering", "people", "I", "teach", "HTML", "CSS", "JS", "React", "Python"]
|
||||
|
||||
13
|
||||
```
|
||||
|
||||
1. Nel seguente carrello della spesa aggiungere, rimuovere, modificare gli articoli
|
||||
|
||||
```js
|
||||
const shoppingCart = ['Milk', 'Coffee', 'Tea', 'Honey']
|
||||
```
|
||||
|
||||
- aggiungere "Carne" all'inizio del carrello se non è già stato aggiunto
|
||||
- aggiungere "Zucchero" alla fine del carrello se non è già stato aggiunto
|
||||
- rimuovere "Miele" se si è allergici al miele
|
||||
- modificare il tè in "Tè verde".
|
||||
1. Nell'array dei Paesi controllare se 'Etiopia' esiste nell'array, se esiste stampare 'ETIOPIA'. Se non esiste, aggiungerlo all'elenco dei paesi.
|
||||
1. Nell'array webTechs verificare se Sass esiste nell'array e se esiste stampare 'Sass è un preprocesso CSS'. Se non esiste, aggiungere Sass all'array e stampare l'array.
|
||||
1. Concatenare le due variabili seguenti e memorizzarle in una variabile fullStack.
|
||||
|
||||
```js
|
||||
const frontEnd = ['HTML', 'CSS', 'JS', 'React', 'Redux']
|
||||
const backEnd = ['Node','Express', 'MongoDB']
|
||||
|
||||
console.log(fullStack)
|
||||
```
|
||||
|
||||
```sh
|
||||
["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"]
|
||||
```
|
||||
|
||||
### Esercizio: Livello 3
|
||||
|
||||
1. Di seguito è riportata una serie di 10 studenti di età:
|
||||
|
||||
```js
|
||||
const ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
|
||||
```
|
||||
|
||||
- Ordinare l'array e trovare l'età minima e massima
|
||||
- Trovare l'età mediana (un elemento centrale o due elementi centrali divisi per due)
|
||||
- Trovare l'età media (tutti gli elementi divisi per il numero di elementi)
|
||||
- Trovare l'intervallo delle età (max meno min)
|
||||
- Confrontare il valore di (min - media) e (max - media), utilizzando il metodo _abs()_.
|
||||
1.Tagliare i primi dieci Paesi dalla [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
|
||||
1. Trovare il/i Paese/i centrale/i nella [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
|
||||
2. Dividere l'array di paesi in due array uguali se è pari. Se l'array dei paesi non è pari, un altro paese per la prima metà.
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 4](../04_Day_Conditionals/04_day_Conditionals.md) | [Day 6 >>](../06_Day_Loops/06_day_loops.md)
|
@ -0,0 +1,484 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Loops</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 5](../05_Day_Arrays/05_day_arrays.md) | [Day 7 >>](../07_Day_Functions/07_day_functions.md)
|
||||
|
||||

|
||||
|
||||
- [📔 Giorno 6](#-day-6)
|
||||
- [Loops](#loops)
|
||||
- [for Loop](#for-loop)
|
||||
- [while loop](#while-loop)
|
||||
- [do while loop](#do-while-loop)
|
||||
- [for of loop](#for-of-loop)
|
||||
- [break](#break)
|
||||
- [continue](#continue)
|
||||
- [💻 Esercizi:Day 6](#-exercisesday-6)
|
||||
- [Esercizi: Livello 1](#exercises-level-1)
|
||||
- [Esercizi: Livello 2](#exercises-level-2)
|
||||
- [Esercizi: Livello 3](#exercises-level-3)
|
||||
|
||||
# 📔 Giorno 6
|
||||
|
||||
## Loops
|
||||
|
||||
La maggior parte delle attività che svolgiamo nella vita sono piene di ripetizioni. Immaginate se vi chiedessi di stampare da 0 a 100 usando console.log(). Per eseguire questo semplice compito potreste impiegare dai 2 ai 5 minuti; questo tipo di attività noiosa e ripetitiva può essere eseguita con un ciclo. Se si preferisce guardare i video, è possibile consultare la pagina [video tutorials](https://www.youtube.com/channel/UCM4xOopkYiPwJqyKsSqL9mw)
|
||||
|
||||
Nei linguaggi di programmazione, per svolgere attività ripetitive si utilizzano diversi tipi di loop. I seguenti esempi sono i cicli comunemente utilizzati in JavaScript e in altri linguaggi di programmazione.
|
||||
|
||||
### for Loop
|
||||
|
||||
```js
|
||||
// For loop structure
|
||||
for(initialization, condition, increment/decrement){
|
||||
// code goes here
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
for(let i = 0; i <= 5; i++){
|
||||
console.log(i)
|
||||
}
|
||||
|
||||
// 0 1 2 3 4 5
|
||||
```
|
||||
|
||||
```js
|
||||
for(let i = 5; i >= 0; i--){
|
||||
console.log(i)
|
||||
}
|
||||
|
||||
// 5 4 3 2 1 0
|
||||
```
|
||||
|
||||
```js
|
||||
for(let i = 0; i <= 5; i++){
|
||||
console.log(`${i} * ${i} = ${i * i}`)
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
0 * 0 = 0
|
||||
1 * 1 = 1
|
||||
2 * 2 = 4
|
||||
3 * 3 = 9
|
||||
4 * 4 = 16
|
||||
5 * 5 = 25
|
||||
```
|
||||
|
||||
```js
|
||||
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland']
|
||||
const newArr = []
|
||||
for(let i = 0; i < countries.length; i++){
|
||||
newArr.push(countries[i].toUpperCase())
|
||||
}
|
||||
|
||||
// ["FINLAND", "SWEDEN", "DENMARK", "NORWAY", "ICELAND"]
|
||||
```
|
||||
|
||||
Aggiunta di tutti gli elementi dell'array
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
let sum = 0
|
||||
for(let i = 0; i < numbers.length; i++){
|
||||
sum = sum + numbers[i] // can be shorten, sum += numbers[i]
|
||||
|
||||
}
|
||||
|
||||
console.log(sum) // 15
|
||||
```
|
||||
|
||||
Creare un nuovo array basato sull'array esistente
|
||||
|
||||
```js
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
const newArr = []
|
||||
let sum = 0
|
||||
for(let i = 0; i < numbers.length; i++){
|
||||
newArr.push( numbers[i] ** 2)
|
||||
|
||||
}
|
||||
|
||||
console.log(newArr) // [1, 4, 9, 16, 25]
|
||||
```
|
||||
|
||||
```js
|
||||
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
|
||||
const newArr = []
|
||||
for(let i = 0; i < countries.length; i++){
|
||||
newArr.push(countries[i].toUpperCase())
|
||||
}
|
||||
|
||||
console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
|
||||
```
|
||||
|
||||
### while loop
|
||||
|
||||
```js
|
||||
let i = 0
|
||||
while (i <= 5) {
|
||||
console.log(i)
|
||||
i++
|
||||
}
|
||||
|
||||
// 0 1 2 3 4 5
|
||||
```
|
||||
|
||||
### do while loop
|
||||
|
||||
```js
|
||||
let i = 0
|
||||
do {
|
||||
console.log(i)
|
||||
i++
|
||||
} while (i <= 5)
|
||||
|
||||
// 0 1 2 3 4 5
|
||||
```
|
||||
|
||||
### for of loop
|
||||
|
||||
Utilizziamo il ciclo for per gli array. È un modo molto pratico per iterare un array se non siamo interessati all'indice di ogni elemento dell'array.
|
||||
|
||||
```js
|
||||
for (const element of arr) {
|
||||
// code goes here
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
const numbers = [1, 2, 3, 4, 5]
|
||||
|
||||
for (const num of numbers) {
|
||||
console.log(num)
|
||||
}
|
||||
|
||||
// 1 2 3 4 5
|
||||
|
||||
for (const num of numbers) {
|
||||
console.log(num * num)
|
||||
}
|
||||
|
||||
// 1 4 9 16 25
|
||||
|
||||
// adding all the numbers in the array
|
||||
let sum = 0
|
||||
for (const num of numbers) {
|
||||
sum = sum + num
|
||||
// can be also shorten like this, sum += num
|
||||
// after this we will use the shorter synthax(+=, -=, *=, /= etc)
|
||||
}
|
||||
console.log(sum) // 15
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
]
|
||||
|
||||
for (const tech of webTechs) {
|
||||
console.log(tech.toUpperCase())
|
||||
}
|
||||
|
||||
// HTML CSS JAVASCRIPT REACT NODE MONGODB
|
||||
|
||||
for (const tech of webTechs) {
|
||||
console.log(tech[0]) // get only the first letter of each element, H C J R N M
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
```js
|
||||
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
|
||||
const newArr = []
|
||||
for(const country of countries){
|
||||
newArr.push(country.toUpperCase())
|
||||
}
|
||||
|
||||
console.log(newArr) // ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
|
||||
```
|
||||
|
||||
### break
|
||||
|
||||
Break viene utilizzato per interrompere un ciclo.
|
||||
|
||||
```js
|
||||
for(let i = 0; i <= 5; i++){
|
||||
if(i == 3){
|
||||
break
|
||||
}
|
||||
console.log(i)
|
||||
}
|
||||
|
||||
// 0 1 2
|
||||
```
|
||||
|
||||
Il codice precedente si arresta se viene trovato 3 nel processo di iterazione.
|
||||
|
||||
### continue
|
||||
|
||||
Utilizziamo la parola chiave *continue* per saltare una determinata iterazione.
|
||||
|
||||
```js
|
||||
for(let i = 0; i <= 5; i++){
|
||||
if(i == 3){
|
||||
continue
|
||||
}
|
||||
console.log(i)
|
||||
}
|
||||
|
||||
// 0 1 2 4 5
|
||||
```
|
||||
|
||||
🌕 Sei molto coraggioso, sei arrivato fino a questo punto. Ora hai acquisito il potere di automatizzare compiti ripetitivi e noiosi. Hai appena completato le sfide del sesto giorno e sei a 6 passi dalla vostra strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
|
||||
|
||||
## 💻 Esercizi:Day 6
|
||||
|
||||
### Esercizi: Livello 1
|
||||
|
||||
```js
|
||||
const countries = [
|
||||
'Albania',
|
||||
'Bolivia',
|
||||
'Canada',
|
||||
'Denmark',
|
||||
'Ethiopia',
|
||||
'Finland',
|
||||
'Germany',
|
||||
'Hungary',
|
||||
'Ireland',
|
||||
'Japan',
|
||||
'Kenya'
|
||||
]
|
||||
|
||||
const webTechs = [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Redux',
|
||||
'Node',
|
||||
'MongoDB'
|
||||
]
|
||||
|
||||
const mernStack = ['MongoDB', 'Express', 'React', 'Node']
|
||||
```
|
||||
|
||||
1. Iterare da 0 a 10 usando il ciclo for, fare lo stesso usando il ciclo while e do while
|
||||
2. Iterare da 10 a 0 usando il ciclo for, fare lo stesso usando il ciclo while e do while
|
||||
3. Iterare da 0 a n usando il ciclo for
|
||||
4. Scrivete un ciclo che esegua il seguente schema utilizzando console.log():
|
||||
|
||||
```js
|
||||
#
|
||||
##
|
||||
###
|
||||
####
|
||||
#####
|
||||
######
|
||||
#######
|
||||
```
|
||||
|
||||
5. Utilizzare il loop per stampare il seguente schema:
|
||||
|
||||
```sh
|
||||
0 x 0 = 0
|
||||
1 x 1 = 1
|
||||
2 x 2 = 4
|
||||
3 x 3 = 9
|
||||
4 x 4 = 16
|
||||
5 x 5 = 25
|
||||
6 x 6 = 36
|
||||
7 x 7 = 49
|
||||
8 x 8 = 64
|
||||
9 x 9 = 81
|
||||
10 x 10 = 100
|
||||
```
|
||||
|
||||
6. Utilizzando il loop stampate il seguente schema
|
||||
|
||||
```sh
|
||||
i i^2 i^3
|
||||
0 0 0
|
||||
1 1 1
|
||||
2 4 8
|
||||
3 9 27
|
||||
4 16 64
|
||||
5 25 125
|
||||
6 36 216
|
||||
7 49 343
|
||||
8 64 512
|
||||
9 81 729
|
||||
10 100 1000
|
||||
```
|
||||
|
||||
7. Utilizzare il ciclo for per iterare da 0 a 100 e stampare solo i numeri pari.
|
||||
8. Usare il ciclo for per iterare da 0 a 100 e stampare solo i numeri dispari
|
||||
9. Usare il ciclo for per iterare da 0 a 100 e stampare solo i numeri primi
|
||||
10. Usare il ciclo for per iterare da 0 a 100 e stampare la somma di tutti i numeri.
|
||||
|
||||
```sh
|
||||
The sum of all numbers from 0 to 100 is 5050.
|
||||
```
|
||||
|
||||
11. Utilizzare il ciclo for per iterare da 0 a 100 e stampare la somma di tutti i pari e la somma di tutti i dispari.
|
||||
|
||||
```sh
|
||||
The sum of all evens from 0 to 100 is 2550. And the sum of all odds from 0 to 100 is 2500.
|
||||
```
|
||||
|
||||
12. Utilizzare il ciclo for per iterare da 0 a 100 e stampare la somma di tutti i pari e la somma di tutti i dispari. Stampa della somma dei pari e della somma dei dispari come array
|
||||
|
||||
```sh
|
||||
[2550, 2500]
|
||||
```
|
||||
|
||||
13. Sviluppare un piccolo script che generi un array di 5 numeri casuali.
|
||||
14. Sviluppare un piccolo script che generi un array di 5 numeri casuali e i numeri devono essere unici.
|
||||
15. Sviluppare un piccolo script che generi un id casuale di sei caratteri:
|
||||
|
||||
```sh
|
||||
5j2khz
|
||||
```
|
||||
|
||||
### Esercizi: Livello 2
|
||||
|
||||
1. Sviluppare un piccolo script che generi un numero qualsiasi di caratteri di id casuale:
|
||||
|
||||
```sh
|
||||
fe3jo1gl124g
|
||||
```
|
||||
|
||||
```sh
|
||||
xkqci4utda1lmbelpkm03rba
|
||||
```
|
||||
|
||||
1. Scrivere uno script che generi un numero esadecimale casuale.
|
||||
|
||||
```sh
|
||||
'#ee33df'
|
||||
```
|
||||
|
||||
1. Scrivere uno script che genera un numero di colore rgb casuale.
|
||||
|
||||
```sh
|
||||
rgb(240,180,80)
|
||||
```
|
||||
|
||||
1. Utilizzando l'array di paesi di cui sopra, creare il seguente nuovo array.
|
||||
|
||||
```sh
|
||||
["ALBANIA", "BOLIVIA", "CANADA", "DENMARK", "ETHIOPIA", "FINLAND", "GERMANY", "HUNGARY", "IRELAND", "JAPAN", "KENYA"]
|
||||
```
|
||||
|
||||
1. Utilizzando l'array di paesi di cui sopra, creare un array per la lunghezza dei paesi"..
|
||||
|
||||
```sh
|
||||
[7, 7, 6, 7, 8, 7, 7, 7, 7, 5, 5]
|
||||
```
|
||||
|
||||
1. Utilizzare l'array dei paesi per creare il seguente array di array:
|
||||
|
||||
```sh
|
||||
[
|
||||
['Albania', 'ALB', 7],
|
||||
['Bolivia', 'BOL', 7],
|
||||
['Canada', 'CAN', 6],
|
||||
['Denmark', 'DEN', 7],
|
||||
['Ethiopia', 'ETH', 8],
|
||||
['Finland', 'FIN', 7],
|
||||
['Germany', 'GER', 7],
|
||||
['Hungary', 'HUN', 7],
|
||||
['Ireland', 'IRE', 7],
|
||||
['Iceland', 'ICE', 7],
|
||||
['Japan', 'JAP', 5],
|
||||
['Kenya', 'KEN', 5]
|
||||
]
|
||||
```
|
||||
|
||||
2. Nell'array di paesi di cui sopra, verificare se ci sono uno o più paesi contenenti la parola "terra". Se ci sono paesi contenenti "terra", stamparli come array. Se non c'è nessun paese contenente la parola "terra", stampare "Tutti questi paesi sono senza terra".
|
||||
|
||||
```sh
|
||||
['Finland','Ireland', 'Iceland']
|
||||
```
|
||||
|
||||
3. Nell'array di paesi di cui sopra, verificare se esiste un paese o se i paesi terminano con la sottostringa 'ia'. Se ci sono paesi che terminano con, stamparli come array. Se non c'è nessun paese che contiene la parola 'ai', viene stampato 'Questi sono i paesi che terminano senza ia'.
|
||||
|
||||
```sh
|
||||
['Albania', 'Bolivia','Ethiopia']
|
||||
```
|
||||
|
||||
4. Utilizzando l'array di paesi di cui sopra, trovare il paese che contiene il maggior numero di caratteri.
|
||||
|
||||
```sh
|
||||
Ethiopia
|
||||
```
|
||||
|
||||
5. Utilizzando l'array di paesi di cui sopra, trovare il paese che contiene solo 5 caratteri.
|
||||
|
||||
```sh
|
||||
['Japan', 'Kenya']
|
||||
```
|
||||
|
||||
6. Trovare la parola più lunga nell'array WebTechs
|
||||
7. Utilizzate l'array WebTechs per creare il seguente array di array:
|
||||
|
||||
```sh
|
||||
[["HTML", 4], ["CSS", 3],["JavaScript", 10],["React", 5],["Redux", 5],["Node", 4],["MongoDB", 7]]
|
||||
```
|
||||
|
||||
8. Un'applicazione creata utilizzando MongoDB, Express, React e Node è chiamata applicazione MERN stack. Creare l'acronimo MERN utilizzando l'array mernStack.
|
||||
9. Iterare l'array ["HTML", "CSS", "JS", "React", "Redux", "Node", "Express", "MongoDB"] utilizzando un ciclo for o for of e stampare gli elementi.
|
||||
10. Questo è un array di frutta, ['banana', 'arancia', 'mango', 'limone'] invertire l'ordine usando un ciclo senza usare un metodo inverso.
|
||||
11. Stampate tutti gli elementi dell'array come mostrato di seguito.
|
||||
|
||||
```js
|
||||
const fullStack = [
|
||||
['HTML', 'CSS', 'JS', 'React'],
|
||||
['Node', 'Express', 'MongoDB']
|
||||
]
|
||||
````
|
||||
|
||||
```sh
|
||||
HTML
|
||||
CSS
|
||||
JS
|
||||
REACT
|
||||
NODE
|
||||
EXPRESS
|
||||
MONGODB
|
||||
```
|
||||
|
||||
### Esercizi: Livello 3
|
||||
|
||||
1. Copiare l'array dei paesi (evitare la mutazione)
|
||||
1. Gli array sono mutabili. Creare una copia dell'array che non modifichi l'originale. Ordinare l'array copiato e memorizzarlo in una variabile ordinataPaesi
|
||||
1. Ordinare l'array WebTechs e l'array mernStack
|
||||
1. Estrarre tutti i paesi che contengono la parola "terra" dall'array [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e stamparla come array
|
||||
1. Trovare il paese che contiene il maggior numero di caratteri nella [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
|
||||
1. Estrarre tutti i paesi che contengono la parola "terra" dall'[countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e stamparli come array
|
||||
1. Estrarre tutti i paesi che contengono solo quattro caratteri dall'[countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e stamparli come array
|
||||
1. Estraete tutti i paesi che contengono due o più parole dall'[countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e stampateli come array
|
||||
1. Invertire la [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js) e scrivere in maiuscolo ogni paese e memorizzarlo come matrice
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 5](../05_Day_Arrays/05_day_arrays.md) | [Day 7 >>](../07_Day_Functions/07_day_functions.md)
|
@ -0,0 +1,595 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Objects</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
|
||||
[<< Day 7](../07_Day_Functions/07_day_functions.md) | [Day 9 >>](../09_Day_Higher_order_functions/09_day_higher_order_functions.md)
|
||||
|
||||

|
||||
|
||||
- [📔 Giorno 8](#-day-8)
|
||||
- [Scope](#scope)
|
||||
- [Window Global Object](#window-global-object)
|
||||
- [Global scope](#global-scope)
|
||||
- [Local scope](#local-scope)
|
||||
- [📔 Object](#-object)
|
||||
- [Creating an empty object](#creating-an-empty-object)
|
||||
- [Creating an objecting with values](#creating-an-objecting-with-values)
|
||||
- [Getting values from an object](#getting-values-from-an-object)
|
||||
- [Creating object methods](#creating-object-methods)
|
||||
- [Setting new key for an object](#setting-new-key-for-an-object)
|
||||
- [Object Methods](#object-methods)
|
||||
- [Getting object keys using Object.keys()](#getting-object-keys-using-objectkeys)
|
||||
- [Getting object values using Object.values()](#getting-object-values-using-objectvalues)
|
||||
- [Getting object keys and values using Object.entries()](#getting-object-keys-and-values-using-objectentries)
|
||||
- [Checking properties using hasOwnProperty()](#checking-properties-using-hasownproperty)
|
||||
- [💻 Esercizi](#-exercises)
|
||||
- [Esercizi: Livello 1](#exercises-level-1)
|
||||
- [Esercizi: Livello 2](#exercises-level-2)
|
||||
- [Esercizi: Livello 3](#exercises-level-3)
|
||||
|
||||
# 📔 Giorno 8
|
||||
|
||||
## Scope
|
||||
|
||||
Variable is the fundamental part in programming. We declare variable to store different data types. To declare a variable we use the key word _var_, _let_ and _const_. A variable can be declared at different scope. In this section, we will see the scope variables, scope of variables when we use var or let.
|
||||
Variables scopes can be:
|
||||
|
||||
- Global
|
||||
- Local
|
||||
|
||||
Variable can be declared globally or locally scope. We will see both global and local scope.
|
||||
Anything declared without let, var or const is scoped at global level.
|
||||
|
||||
Let us imagine that we have a scope.js file.
|
||||
|
||||
### Window Global Object
|
||||
|
||||
Without using console.log() open your browser and check, you will see the value of a and b if you write a or b on the browser. That means a and b are already available in the window.
|
||||
|
||||
```js
|
||||
//scope.js
|
||||
a = 'JavaScript' // declaring a variable without let or const make it available in window object and this found anywhere
|
||||
b = 10 // this is a global scope variable and found in the window object
|
||||
function letsLearnScope() {
|
||||
console.log(a, b)
|
||||
if (true) {
|
||||
console.log(a, b)
|
||||
}
|
||||
}
|
||||
console.log(a, b) // accessible
|
||||
```
|
||||
|
||||
### Global scope
|
||||
|
||||
A globally declared variable can be accessed every where in the same file. But the term global is relative. It can be global to the file or it can be global relative to some block of codes.
|
||||
|
||||
```js
|
||||
//scope.js
|
||||
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
|
||||
let b = 10 // is a global scope it will be found anywhere in this file
|
||||
function letsLearnScope() {
|
||||
console.log(a, b) // JavaScript 10, accessible
|
||||
if (true) {
|
||||
let a = 'Python'
|
||||
let b = 100
|
||||
console.log(a, b) // Python 100
|
||||
}
|
||||
console.log(a, b)
|
||||
}
|
||||
letsLearnScope()
|
||||
console.log(a, b) // JavaScript 10, accessible
|
||||
```
|
||||
|
||||
### Local scope
|
||||
|
||||
A variable declared as local can be accessed only in certain block code.
|
||||
|
||||
- Block Scope
|
||||
- Function Scope
|
||||
|
||||
```js
|
||||
//scope.js
|
||||
let a = 'JavaScript' // is a global scope it will be found anywhere in this file
|
||||
let b = 10 // is a global scope it will be found anywhere in this file
|
||||
// Function scope
|
||||
function letsLearnScope() {
|
||||
console.log(a, b) // JavaScript 10, accessible
|
||||
let value = false
|
||||
// block scope
|
||||
if (true) {
|
||||
// we can access from the function and outside the function but
|
||||
// variables declared inside the if will not be accessed outside the if block
|
||||
let a = 'Python'
|
||||
let b = 20
|
||||
let c = 30
|
||||
let d = 40
|
||||
value = !value
|
||||
console.log(a, b, c, value) // Python 20 30 true
|
||||
}
|
||||
// we can not access c because c's scope is only the if block
|
||||
console.log(a, b, value) // JavaScript 10 true
|
||||
}
|
||||
letsLearnScope()
|
||||
console.log(a, b) // JavaScript 10, accessible
|
||||
```
|
||||
|
||||
Now, you have an understanding of scope. A variable declared with *var* only scoped to function but variable declared with *let* or *const* is block scope(function block, if block, loop block, etc). Block in JavaScript is a code in between two curly brackets ({}).
|
||||
|
||||
```js
|
||||
//scope.js
|
||||
function letsLearnScope() {
|
||||
var gravity = 9.81
|
||||
console.log(gravity)
|
||||
|
||||
}
|
||||
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
|
||||
|
||||
if (true){
|
||||
var gravity = 9.81
|
||||
console.log(gravity) // 9.81
|
||||
}
|
||||
console.log(gravity) // 9.81
|
||||
|
||||
for(var i = 0; i < 3; i++){
|
||||
console.log(i) // 0, 1, 2
|
||||
}
|
||||
console.log(i) // 3
|
||||
|
||||
```
|
||||
|
||||
In ES6 and above there is *let* and *const*, so you will not suffer from the sneakiness of *var*. When we use *let* our variable is block scoped and it will not infect other parts of our code.
|
||||
|
||||
```js
|
||||
//scope.js
|
||||
function letsLearnScope() {
|
||||
// you can use let or const, but gravity is constant I prefer to use const
|
||||
const gravity = 9.81
|
||||
console.log(gravity)
|
||||
|
||||
}
|
||||
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
|
||||
|
||||
if (true){
|
||||
const gravity = 9.81
|
||||
console.log(gravity) // 9.81
|
||||
}
|
||||
// console.log(gravity), Uncaught ReferenceError: gravity is not defined
|
||||
|
||||
for(let i = 0; i < 3; i++){
|
||||
console.log(i) // 0, 1, 2
|
||||
}
|
||||
// console.log(i), Uncaught ReferenceError: i is not defined
|
||||
|
||||
```
|
||||
|
||||
The scope *let* and *const* are the same. The difference is only reassigning. We can not change or reassign the value of the `const` variable. I would strongly suggest you to use *let* and *const*, by using *let* and *const* you will write clean code and avoid hard to debug mistakes. As a rule of thumb, you can use *let* for any value which change, *const* for any constant value, and for an array, object, arrow function and function expression.
|
||||
|
||||
## 📔 Object
|
||||
|
||||
Everything can be an object and objects do have properties and properties have values, so an object is a key value pair. The order of the key is not reserved, or there is no order.
|
||||
To create an object literal, we use two curly brackets.
|
||||
|
||||
### Creating an empty object
|
||||
|
||||
An empty object
|
||||
|
||||
```js
|
||||
const person = {}
|
||||
```
|
||||
|
||||
### Creating an objecting with values
|
||||
|
||||
Now, the person object has firstName, lastName, age, location, skills and isMarried properties. The value of properties or keys could be a string, number, boolean, an object, null, undefined or a function.
|
||||
|
||||
Let us see some examples of object. Each key has a value in the object.
|
||||
|
||||
```js
|
||||
const rectangle = {
|
||||
length: 20,
|
||||
width: 20
|
||||
}
|
||||
console.log(rectangle) // {length: 20, width: 20}
|
||||
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js'
|
||||
],
|
||||
isMarried: true
|
||||
}
|
||||
console.log(person)
|
||||
```
|
||||
|
||||
### Getting values from an object
|
||||
|
||||
We can access values of object using two methods:
|
||||
|
||||
- using . followed by key name if the key-name is a one word
|
||||
- using square bracket and a quote
|
||||
|
||||
```js
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js'
|
||||
],
|
||||
getFullName: function() {
|
||||
return `${this.firstName}${this.lastName}`
|
||||
},
|
||||
'phone number': '+3584545454545'
|
||||
}
|
||||
|
||||
// accessing values using .
|
||||
console.log(person.firstName)
|
||||
console.log(person.lastName)
|
||||
console.log(person.age)
|
||||
console.log(person.location) // undefined
|
||||
|
||||
// value can be accessed using square bracket and key name
|
||||
console.log(person['firstName'])
|
||||
console.log(person['lastName'])
|
||||
console.log(person['age'])
|
||||
console.log(person['age'])
|
||||
console.log(person['location']) // undefined
|
||||
|
||||
// for instance to access the phone number we only use the square bracket method
|
||||
console.log(person['phone number'])
|
||||
```
|
||||
|
||||
### Creating object methods
|
||||
|
||||
Now, the person object has getFullName properties. The getFullName is function inside the person object and we call it an object method. The _this_ key word refers to the object itself. We can use the word _this_ to access the values of different properties of the object. We can not use an arrow function as object method because the word this refers to the window inside an arrow function instead of the object itself. Example of object:
|
||||
|
||||
```js
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js'
|
||||
],
|
||||
getFullName: function() {
|
||||
return `${this.firstName} ${this.lastName}`
|
||||
}
|
||||
}
|
||||
|
||||
console.log(person.getFullName())
|
||||
// Asabeneh Yetayeh
|
||||
```
|
||||
|
||||
### Setting new key for an object
|
||||
|
||||
An object is a mutable data structure and we can modify the content of an object after it gets created.
|
||||
|
||||
Setting a new keys in an object
|
||||
|
||||
```js
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'React',
|
||||
'Node',
|
||||
'MongoDB',
|
||||
'Python',
|
||||
'D3.js'
|
||||
],
|
||||
getFullName: function() {
|
||||
return `${this.firstName} ${this.lastName}`
|
||||
}
|
||||
}
|
||||
person.nationality = 'Ethiopian'
|
||||
person.country = 'Finland'
|
||||
person.title = 'teacher'
|
||||
person.skills.push('Meteor')
|
||||
person.skills.push('SasS')
|
||||
person.isMarried = true
|
||||
|
||||
person.getPersonInfo = function() {
|
||||
let skillsWithoutLastSkill = this.skills
|
||||
.splice(0, this.skills.length - 1)
|
||||
.join(', ')
|
||||
let lastSkill = this.skills.splice(this.skills.length - 1)[0]
|
||||
|
||||
let skills = `${skillsWithoutLastSkill}, and ${lastSkill}`
|
||||
let fullName = this.getFullName()
|
||||
let statement = `${fullName} is a ${this.title}.\nHe lives in ${this.country}.\nHe teaches ${skills}.`
|
||||
return statement
|
||||
}
|
||||
console.log(person)
|
||||
console.log(person.getPersonInfo())
|
||||
```
|
||||
|
||||
```sh
|
||||
Asabeneh Yetayeh is a teacher.
|
||||
He lives in Finland.
|
||||
He teaches HTML, CSS, JavaScript, React, Node, MongoDB, Python, D3.js, Meteor, and SasS.
|
||||
```
|
||||
|
||||
### Object Methods
|
||||
|
||||
There are different methods to manipulate an object. Let us see some of the available methods.
|
||||
|
||||
_Object.assign_: To copy an object without modifying the original object
|
||||
|
||||
```js
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city:'Helsinki',
|
||||
skills: ['HTML', 'CSS', 'JS'],
|
||||
title: 'teacher',
|
||||
address: {
|
||||
street: 'Heitamienkatu 16',
|
||||
pobox: 2002,
|
||||
city: 'Helsinki'
|
||||
},
|
||||
getPersonInfo: function() {
|
||||
return `I am ${this.firstName} and I live in ${this.city}, ${this.country}. I am ${this.age}.`
|
||||
}
|
||||
}
|
||||
|
||||
//Object methods: Object.assign, Object.keys, Object.values, Object.entries
|
||||
//hasOwnProperty
|
||||
|
||||
const copyPerson = Object.assign({}, person)
|
||||
console.log(copyPerson)
|
||||
```
|
||||
|
||||
#### Getting object keys using Object.keys()
|
||||
|
||||
_Object.keys_: To get the keys or properties of an object as an array
|
||||
|
||||
```js
|
||||
const keys = Object.keys(copyPerson)
|
||||
console.log(keys) //['firstName', 'age', 'country','city', 'skills','title', 'address', 'getPersonInfo']
|
||||
const address = Object.keys(copyPerson.address)
|
||||
console.log(address) //['street', 'pobox', 'city']
|
||||
```
|
||||
|
||||
#### Getting object values using Object.values()
|
||||
|
||||
_Object.values_:To get values of an object as an array
|
||||
|
||||
```js
|
||||
const values = Object.values(copyPerson)
|
||||
console.log(values)
|
||||
```
|
||||
|
||||
#### Getting object keys and values using Object.entries()
|
||||
|
||||
_Object.entries_:To get the keys and values in an array
|
||||
|
||||
```js
|
||||
const entries = Object.entries(copyPerson)
|
||||
console.log(entries)
|
||||
```
|
||||
|
||||
#### Checking properties using hasOwnProperty()
|
||||
|
||||
_hasOwnProperty_: To check if a specific key or property exist in an object
|
||||
|
||||
```js
|
||||
console.log(copyPerson.hasOwnProperty('name'))
|
||||
console.log(copyPerson.hasOwnProperty('score'))
|
||||
```
|
||||
|
||||
🌕 You are astonishing. Now, you are super charged with the power of objects. You have just completed day 8 challenges and you are 8 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## 💻 Esercizi
|
||||
|
||||
### Esercizi: Livello 1
|
||||
|
||||
1. Create an empty object called dog
|
||||
1. Print the the dog object on the console
|
||||
1. Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return _woof woof_
|
||||
1. Get name, legs, color, age and bark value from the dog object
|
||||
1. Set new properties the dog object: breed, getDogInfo
|
||||
|
||||
### Esercizi: Livello 2
|
||||
|
||||
1. Find the person who has many skills in the users object.
|
||||
1. Count logged in users, count users having greater than equal to 50 points from the following object.
|
||||
|
||||
````js
|
||||
const users = {
|
||||
Alex: {
|
||||
email: 'alex@alex.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 30
|
||||
},
|
||||
Asab: {
|
||||
email: 'asab@asab.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
|
||||
age: 25,
|
||||
isLoggedIn: false,
|
||||
points: 50
|
||||
},
|
||||
Brook: {
|
||||
email: 'daniel@daniel.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
|
||||
age: 30,
|
||||
isLoggedIn: true,
|
||||
points: 50
|
||||
},
|
||||
Daniel: {
|
||||
email: 'daniel@alex.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
},
|
||||
John: {
|
||||
email: 'john@john.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
|
||||
age: 20,
|
||||
isLoggedIn: true,
|
||||
points: 50
|
||||
},
|
||||
Thomas: {
|
||||
email: 'thomas@thomas.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
},
|
||||
Paul: {
|
||||
email: 'paul@paul.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
}
|
||||
}```
|
||||
|
||||
1. Find people who are MERN stack developer from the users object
|
||||
1. Set your name in the users object without modifying the original users object
|
||||
1. Get all keys or properties of users object
|
||||
1. Get all the values of users object
|
||||
1. Use the countries object to print a country name, capital, populations and languages.
|
||||
|
||||
### Esercizi: Livello 3
|
||||
|
||||
1. Create an object literal called _personAccount_. It has _firstName, lastName, incomes, expenses_ properties and it has _totalIncome, totalExpense, accountInfo,addIncome, addExpense_ and _accountBalance_ methods. Incomes is a set of incomes and its description and expenses is a set of incomes and its description.
|
||||
2. **** Questions:2, 3 and 4 are based on the following two arrays:users and products ()
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{
|
||||
_id: 'ab12ex',
|
||||
username: 'Alex',
|
||||
email: 'alex@alex.com',
|
||||
password: '123123',
|
||||
createdAt:'08/01/2020 9:00 AM',
|
||||
isLoggedIn: false
|
||||
},
|
||||
{
|
||||
_id: 'fg12cy',
|
||||
username: 'Asab',
|
||||
email: 'asab@asab.com',
|
||||
password: '123456',
|
||||
createdAt:'08/01/2020 9:30 AM',
|
||||
isLoggedIn: true
|
||||
},
|
||||
{
|
||||
_id: 'zwf8md',
|
||||
username: 'Brook',
|
||||
email: 'brook@brook.com',
|
||||
password: '123111',
|
||||
createdAt:'08/01/2020 9:45 AM',
|
||||
isLoggedIn: true
|
||||
},
|
||||
{
|
||||
_id: 'eefamr',
|
||||
username: 'Martha',
|
||||
email: 'martha@martha.com',
|
||||
password: '123222',
|
||||
createdAt:'08/01/2020 9:50 AM',
|
||||
isLoggedIn: false
|
||||
},
|
||||
{
|
||||
_id: 'ghderc',
|
||||
username: 'Thomas',
|
||||
email: 'thomas@thomas.com',
|
||||
password: '123333',
|
||||
createdAt:'08/01/2020 10:00 AM',
|
||||
isLoggedIn: false
|
||||
}
|
||||
];
|
||||
|
||||
const products = [
|
||||
{
|
||||
_id: 'eedfcf',
|
||||
name: 'mobile phone',
|
||||
description: 'Huawei Honor',
|
||||
price: 200,
|
||||
ratings: [
|
||||
{ userId: 'fg12cy', rate: 5 },
|
||||
{ userId: 'zwf8md', rate: 4.5 }
|
||||
],
|
||||
likes: []
|
||||
},
|
||||
{
|
||||
_id: 'aegfal',
|
||||
name: 'Laptop',
|
||||
description: 'MacPro: System Darwin',
|
||||
price: 2500,
|
||||
ratings: [],
|
||||
likes: ['fg12cy']
|
||||
},
|
||||
{
|
||||
_id: 'hedfcg',
|
||||
name: 'TV',
|
||||
description: 'Smart TV:Procaster',
|
||||
price: 400,
|
||||
ratings: [{ userId: 'fg12cy', rate: 5 }],
|
||||
likes: ['fg12cy']
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
Imagine you are getting the above users collection from a MongoDB database.
|
||||
a. Create a function called signUp which allows user to add to the collection. If user exists, inform the user that he has already an account.
|
||||
b. Create a function called signIn which allows user to sign in to the application
|
||||
|
||||
3. The products array has three elements and each of them has six properties.
|
||||
a. Create a function called rateProduct which rates the product
|
||||
b. Create a function called averageRating which calculate the average rating of a product
|
||||
|
||||
4. Create a function called likeProduct. This function will helps to like to the product if it is not liked and remove like if it was liked.
|
||||
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 7](../07_Day_Functions/07_day_functions.md) | [Day 9 >>](../09_Day_Higher_order_functions/09_day_higher_order_functions.md)
|
@ -0,0 +1,358 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Console Object Methods</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 12](../12_Day_Regular_expressions/12_day_regular_expressions.md) | [Day 14>>](../14_Day_Error_handling/14_day_error_handling.md)
|
||||
|
||||

|
||||
|
||||
- [Day 13](#day-13)
|
||||
- [Console Object Methods](#console-object-methods)
|
||||
- [console.log()](#consolelog)
|
||||
- [console.warn()](#consolewarn)
|
||||
- [console.error()](#consoleerror)
|
||||
- [console.table()](#consoletable)
|
||||
- [console.time()](#consoletime)
|
||||
- [console.info()](#consoleinfo)
|
||||
- [console.assert()](#consoleassert)
|
||||
- [console.group()](#consolegroup)
|
||||
- [console.count()](#consolecount)
|
||||
- [console.clear()](#consoleclear)
|
||||
- [Esercizi](#exercises)
|
||||
- [Esercizi:Level 1](#exerciseslevel-1)
|
||||
- [Esercizi:Level 2](#exerciseslevel-2)
|
||||
- [Esercizi:Level 3](#exerciseslevel-3)
|
||||
|
||||
# Day 13
|
||||
|
||||
## Console Object Methods
|
||||
|
||||
In this section, we will cover about console and console object methods. Absolute beginners usually do not know which to use: console.log(), document.write() or document.getElementById.
|
||||
|
||||
We use console object methods to show output on the browser console and we use document.write to show output on the browser document(view port). Both methods used only for testing and debugging purposes. The console method is the most popular testing and debugging tool on the browser. We use document.getElementById() when we like to interact with DOM try using JavaScript. We will cover DOM in another section.
|
||||
|
||||
In addition to the famous, console.log() method, the console provides other more methods.
|
||||
|
||||
### console.log()
|
||||
|
||||
We use console.log() to show output on the browser console. We can substitute values and also we can style the logging out put using %c.
|
||||
|
||||
- Showing output on browser console
|
||||
|
||||
```js
|
||||
console.log('30 Days of JavaScript')
|
||||
```
|
||||
|
||||
```sh
|
||||
30 Days of JavaScript
|
||||
```
|
||||
|
||||
- Substitution
|
||||
|
||||
```js
|
||||
console.log('%d %s of JavaScript', 30, 'Days')
|
||||
```
|
||||
|
||||
```sh
|
||||
30 Days of JavaScript
|
||||
```
|
||||
|
||||
- CSS
|
||||
|
||||
We can style logging message using css. Copy the following code and paste it on browser console to see the result.
|
||||
|
||||
```js
|
||||
console.log('%c30 Days Of JavaScript', 'color:green') // log output is green
|
||||
console.log(
|
||||
'%c30 Days%c %cOf%c %cJavaScript%c',
|
||||
'color:green',
|
||||
'',
|
||||
'color:red',
|
||||
'',
|
||||
'color:yellow'
|
||||
) // log output green red and yellow text
|
||||
```
|
||||
|
||||
### console.warn()
|
||||
|
||||
We use console.warn() to give warning on browser. For instance to inform or warn deprecation of version of a package or bad practices. Copy the following code and paste it on browser console to see warning messages.
|
||||
|
||||
```js
|
||||
console.warn('This is a warning')
|
||||
console.warn(
|
||||
'You are using React. Do not touch the DOM. Virtual DOM will take care of handling the DOM!'
|
||||
)
|
||||
console.warn('Warning is different from error')
|
||||
```
|
||||
|
||||
### console.error()
|
||||
|
||||
The console.error() method shows an error messages.
|
||||
|
||||
```js
|
||||
console.error('This is an error message')
|
||||
console.error('We all make mistakes')
|
||||
```
|
||||
|
||||
### console.table()
|
||||
|
||||
The console.table() method display data as a table on the console. Displays tabular data as a table. The console.table() takes one required argument data, which must be an array or an object, and one additional optional parameter columns.
|
||||
|
||||
Let us first start with a simple array. The code below displays a table with two columns. An index column to display the index and value column to display the names
|
||||
|
||||
```js
|
||||
const names = ['Asabeneh', 'Brook', 'David', 'John']
|
||||
console.table(names)
|
||||
```
|
||||
|
||||
Let us also check the result of an object. This creates table with two columns:an index column containing the keys and a value column contain the values of the object.
|
||||
|
||||
```js
|
||||
const user = {
|
||||
name: 'Asabeneh',
|
||||
title: 'Programmer',
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
age: 250
|
||||
}
|
||||
console.table(user)
|
||||
```
|
||||
|
||||
Check the rest of the examples by copying and paste on the browser console.
|
||||
|
||||
```js
|
||||
const countries = [
|
||||
['Finland', 'Helsinki'],
|
||||
['Sweden', 'Stockholm'],
|
||||
['Norway', 'Oslo']
|
||||
]
|
||||
console.table(countries)
|
||||
```
|
||||
|
||||
```js
|
||||
const users = [
|
||||
{
|
||||
name: 'Asabeneh',
|
||||
title: 'Programmer',
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
age: 250
|
||||
},
|
||||
{
|
||||
name: 'Eyob',
|
||||
title: 'Teacher',
|
||||
country: 'Sweden',
|
||||
city: 'London',
|
||||
age: 25
|
||||
},
|
||||
{
|
||||
name: 'Asab',
|
||||
title: 'Instructor',
|
||||
country: 'Norway',
|
||||
city: 'Oslo',
|
||||
age: 22
|
||||
},
|
||||
{
|
||||
name: 'Matias',
|
||||
title: 'Developer',
|
||||
country: 'Denmark',
|
||||
city: 'Copenhagen',
|
||||
age: 28
|
||||
}
|
||||
]
|
||||
console.table(users)
|
||||
```
|
||||
|
||||
### console.time()
|
||||
|
||||
Starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.timeEnd() with the same name, the browser will output the time, in milliseconds, that elapsed since the timer was started.
|
||||
|
||||
```js
|
||||
const countries = [
|
||||
['Finland', 'Helsinki'],
|
||||
['Sweden', 'Stockholm'],
|
||||
['Norway', 'Oslo']
|
||||
]
|
||||
|
||||
console.time('Regular for loop')
|
||||
for (let i = 0; i < countries.length; i++) {
|
||||
console.log(countries[i][0], countries[i][1])
|
||||
}
|
||||
console.timeEnd('Regular for loop')
|
||||
|
||||
console.time('for of loop')
|
||||
for (const [name, city] of countries) {
|
||||
console.log(name, city)
|
||||
}
|
||||
console.timeEnd('for of loop')
|
||||
|
||||
console.time('forEach loop')
|
||||
countries.forEach(([name, city]) => {
|
||||
console.log(name, city)
|
||||
})
|
||||
console.timeEnd('forEach loop')
|
||||
```
|
||||
|
||||
```sh
|
||||
Finland Helsinki
|
||||
Sweden Stockholm
|
||||
Norway Oslo
|
||||
Regular for loop: 0.34716796875ms
|
||||
Finland Helsinki
|
||||
Sweden Stockholm
|
||||
Norway Oslo
|
||||
for of loop: 0.26806640625ms
|
||||
Finland Helsinki
|
||||
Sweden Stockholm
|
||||
Norway Oslo
|
||||
forEach loop: 0.358154296875ms
|
||||
```
|
||||
|
||||
According the above output the regular for loop is slower than for of or forEach loop.
|
||||
|
||||
### console.info()
|
||||
|
||||
It displays information message on browser console.
|
||||
|
||||
```js
|
||||
console.info('30 Days Of JavaScript challenge is trending on Github')
|
||||
console.info('30 Days Of fullStack challenge might be released')
|
||||
console.info('30 Days Of HTML and CSS challenge might be released')
|
||||
```
|
||||
|
||||
### console.assert()
|
||||
|
||||
The console.assert() methods writes an error message to the console if the assertion is false. If the assertion is true, nothing happens. The first parameter is an assertion expression. If this expression is false, an Assertion failed error message will be displayed.
|
||||
|
||||
```js
|
||||
console.assert(4 > 3, '4 is greater than 3') // no result
|
||||
console.assert(3 > 4, '3 is not greater than 4') // Assertion failed: 3 is not greater than 4
|
||||
|
||||
for (let i = 0; i <= 10; i += 1) {
|
||||
let errorMessage = `${i} is not even`
|
||||
console.log('the # is ' + i)
|
||||
console.assert(i % 2 === 0, { number: i, errorMessage: errorMessage })
|
||||
}
|
||||
```
|
||||
|
||||
### console.group()
|
||||
|
||||
The console.group() can help to group different log groups. Copy the following code and paste it on browser console to the groups.
|
||||
|
||||
```js
|
||||
const names = ['Asabeneh', 'Brook', 'David', 'John']
|
||||
const countries = [
|
||||
['Finland', 'Helsinki'],
|
||||
['Sweden', 'Stockholm'],
|
||||
['Norway', 'Oslo']
|
||||
]
|
||||
const user = {
|
||||
name: 'Asabeneh',
|
||||
title: 'Programmer',
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
age: 250
|
||||
}
|
||||
const users = [
|
||||
{
|
||||
name: 'Asabeneh',
|
||||
title: 'Programmer',
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
age: 250
|
||||
},
|
||||
{
|
||||
name: 'Eyob',
|
||||
title: 'Teacher',
|
||||
country: 'Sweden',
|
||||
city: 'London',
|
||||
age: 25
|
||||
},
|
||||
{
|
||||
name: 'Asab',
|
||||
title: 'Instructor',
|
||||
country: 'Norway',
|
||||
city: 'Oslo',
|
||||
age: 22
|
||||
},
|
||||
{
|
||||
name: 'Matias',
|
||||
title: 'Developer',
|
||||
country: 'Denmark',
|
||||
city: 'Copenhagen',
|
||||
age: 28
|
||||
}
|
||||
]
|
||||
|
||||
console.group('Names')
|
||||
console.log(names)
|
||||
console.groupEnd()
|
||||
|
||||
console.group('Countries')
|
||||
console.log(countries)
|
||||
console.groupEnd()
|
||||
|
||||
console.group('Users')
|
||||
console.log(user)
|
||||
console.log(users)
|
||||
console.groupEnd()
|
||||
```
|
||||
|
||||
### console.count()
|
||||
|
||||
It prints the number of times the console.count() is called. It takes a string label parameter. It is very helpful to count the number of times a function is called. In the following example, the console.count() method will run three times
|
||||
|
||||
```js
|
||||
const func = () => {
|
||||
console.count('Function has been called')
|
||||
}
|
||||
func()
|
||||
func()
|
||||
func()
|
||||
```
|
||||
|
||||
```sh
|
||||
Function has been called: 1
|
||||
Function has been called: 2
|
||||
Function has been called: 3
|
||||
```
|
||||
|
||||
### console.clear()
|
||||
|
||||
The console.clear() cleans the browser console.
|
||||
|
||||
🌕 Keep up the good work. Keep pushing, the sky is the limit! You have just completed day 13 challenges and you are 13 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Esercizi:Level 1
|
||||
|
||||
1. Display the countries array as a table
|
||||
2. Display the countries object as a table
|
||||
3. Use console.group() to group logs
|
||||
|
||||
### Esercizi:Level 2
|
||||
|
||||
1. 10 > 2 \* 10 use console.assert()
|
||||
2. Write a warning message using console.warn()
|
||||
3. Write an error message using console.error()
|
||||
|
||||
### Esercizi:Level 3
|
||||
|
||||
1. Check the speed difference among the following loops: while, for, for of, forEach
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 12](../12_Day_Regular_expressions/12_day_regular_expressions.md) | [Day 14>>](../14_Day_Error_handling/14_day_error_handling.md)
|
@ -0,0 +1,193 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Error handling</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md)
|
||||
|
||||

|
||||
|
||||
- [Day 14](#day-14)
|
||||
- [Error Handling](#error-handling)
|
||||
- [Error Types](#error-types)
|
||||
- [Esercizi](#exercises)
|
||||
- [Esercizi:Level 1](#exerciseslevel-1)
|
||||
- [Esercizi: Livello 2](#exercises-level-2)
|
||||
- [Esercizi:Level](#exerciseslevel)
|
||||
|
||||
# Day 14
|
||||
|
||||
## Error Handling
|
||||
|
||||
JavaScript is a loosely-typed language. Some times you will get a runtime error when you try to access an undefined variable or call undefined function etc.
|
||||
|
||||
JavaScript similar to python or Java provides an error-handling mechanism to catch runtime errors using try-catch-finally block.
|
||||
|
||||
```js
|
||||
try {
|
||||
// code that may throw an error
|
||||
} catch (err) {
|
||||
// code to be executed if an error occurs
|
||||
} finally {
|
||||
// code to be executed regardless of an error occurs or not
|
||||
}
|
||||
```
|
||||
|
||||
**try**: wrap suspicious code that may throw an error in try block.The try statement allows us to define a block of code to be tested for errors while it is being executed.
|
||||
|
||||
**catch**: write code to do something in catch block when an error occurs. The catch block can have parameters that will give you error information. Catch block is used to log an error or display specific messages to the user.
|
||||
|
||||
**finally**: finally block will always be executed regardless of the occurrence of an error. The finally block can be used to complete the remaining task or reset variables that might have changed before error occurred in try block.
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
try {
|
||||
let lastName = 'Yetayeh'
|
||||
let fullName = fistName + ' ' + lastName
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
ReferenceError: fistName is not defined
|
||||
at <anonymous>:4:20
|
||||
```
|
||||
|
||||
```js
|
||||
try {
|
||||
let lastName = 'Yetayeh'
|
||||
let fullName = fistName + ' ' + lastName
|
||||
} catch (err) {
|
||||
console.error(err) // we can use console.log() or console.error()
|
||||
} finally {
|
||||
console.log('In any case I will be executed')
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
ReferenceError: fistName is not defined
|
||||
at <anonymous>:4:20
|
||||
In any case it will be executed
|
||||
```
|
||||
|
||||
The catch block take a parameter. It is common to pass e, err or error as a parameter to the catch block. This parameter is an object and it has name and message keys. Lets use the name and message.
|
||||
|
||||
```js
|
||||
try {
|
||||
let lastName = 'Yetayeh'
|
||||
let fullName = fistName + ' ' + lastName
|
||||
} catch (err) {
|
||||
console.log('Name of the error', err.name)
|
||||
console.log('Error message', err.message)
|
||||
} finally {
|
||||
console.log('In any case I will be executed')
|
||||
}
|
||||
```
|
||||
|
||||
```sh
|
||||
Name of the error ReferenceError
|
||||
Error message fistName is not defined
|
||||
In any case I will be executed
|
||||
```
|
||||
|
||||
throw: the throw statement allows us to create a custom error. We can through a string, number, boolean or an object. Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:
|
||||
|
||||
```js
|
||||
throw 'Error2' // generates an exception with a string value
|
||||
throw 42 // generates an exception with the value 42
|
||||
throw true // generates an exception with the value true
|
||||
throw new Error('Required') // generates an error object with the message of Required
|
||||
```
|
||||
|
||||
```js
|
||||
const throwErrorExampleFun = () => {
|
||||
let message
|
||||
let x = prompt('Enter a number: ')
|
||||
try {
|
||||
if (x == '') throw 'empty'
|
||||
if (isNaN(x)) throw 'not a number'
|
||||
x = Number(x)
|
||||
if (x < 5) throw 'too low'
|
||||
if (x > 10) throw 'too high'
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
}
|
||||
}
|
||||
throwErrorExampleFun()
|
||||
```
|
||||
|
||||
### Error Types
|
||||
|
||||
- ReferenceError: An illegal reference has occurred. A ReferenceError is thrown if we use a variable that has not been declared.
|
||||
|
||||
```js
|
||||
let firstName = 'Asabeneh'
|
||||
let fullName = firstName + ' ' + lastName
|
||||
|
||||
console.log(fullName)
|
||||
```
|
||||
|
||||
```sh
|
||||
Uncaught ReferenceError: lastName is not defined
|
||||
at <anonymous>:2:35
|
||||
```
|
||||
|
||||
- SyntaxError: A syntax error has occurred
|
||||
|
||||
```js
|
||||
let square = 2 x 2
|
||||
console.log(square)
|
||||
|
||||
console.log('Hello, world")
|
||||
```
|
||||
|
||||
```sh
|
||||
Uncaught SyntaxError: Unexpected identifier
|
||||
```
|
||||
|
||||
- TypeError: A type error has occurred
|
||||
|
||||
```js
|
||||
let num = 10
|
||||
console.log(num.toLowerCase())
|
||||
```
|
||||
|
||||
```sh
|
||||
Uncaught TypeError: num.toLowerCase is not a function
|
||||
at <anonymous>:2:17
|
||||
```
|
||||
|
||||
These are some of the common error you may face when you write a code. Understanding errors can help you to know what mistakes you made and it will help you to debug your code fast.
|
||||
|
||||
🌕 You are flawless. Now, you knew how to handle errors and you can write robust application which handle unexpected user inputs. You have just completed day 14 challenges and you are 14 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Esercizi:Level 1
|
||||
|
||||
Practice
|
||||
|
||||
### Esercizi: Livello 2
|
||||
|
||||
Practice
|
||||
|
||||
### Esercizi:Level
|
||||
|
||||
Practice
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md)
|
@ -0,0 +1,598 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: JSON</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 15](../15_Day_Classes/15_day_classes.md) | [Day 17 >>](../17_Day_Web_storages/17_day_web_storages.md)
|
||||
|
||||

|
||||
|
||||
- [Day 16](#day-16)
|
||||
- [JSON](#json)
|
||||
- [Converting JSON to JavaScript Object](#converting-json-to-javascript-object)
|
||||
- [JSON.parse()](#jsonparse)
|
||||
- [Using a reviver function with JSON.parse()](#using-a-reviver-function-with-jsonparse)
|
||||
- [Converting Object to JSON](#converting-object-to-json)
|
||||
- [Using a Filter Array with JSON.stringify](#using-a-filter-array-with-jsonstringify)
|
||||
- [Esercizi](#exercises)
|
||||
- [Esercizi Livello 1](#exercises-level-1)
|
||||
- [Esercizi Livello 2](#exercises-level-2)
|
||||
- [Esercizi Livello 3](#exercises-level-3)
|
||||
|
||||
# Day 16
|
||||
|
||||
## JSON
|
||||
|
||||
JSON stands for JavaScript Object Notation. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text or string only. JSON is a light weight data format for storing and transporting. JSON is mostly used when data is sent from a server to a client. JSON is an easier-to-use alternative to XML.
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
{
|
||||
"users":[
|
||||
{
|
||||
"firstName":"Asabeneh",
|
||||
"lastName":"Yetayeh",
|
||||
"age":250,
|
||||
"email":"asab@asb.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Alex",
|
||||
"lastName":"James",
|
||||
"age":25,
|
||||
"email":"alex@alex.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Lidiya",
|
||||
"lastName":"Tekle",
|
||||
"age":28,
|
||||
"email":"lidiya@lidiya.com"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The above JSON example is not much different from a normal object. Then, what is the difference ? The difference is the key of a JSON object should be with double quotes or it should be a string. JavaScript Object and JSON are very similar that we can change JSON to Object and Object to JSON.
|
||||
|
||||
Let us see the above example in more detail, it starts with a curly bracket. Inside the curly bracket, there is "users" key which has a value array. Inside the array we have different objects and each objects has keys, each keys has to have double quotes. For instance, we use "firstNaMe" instead of just firstName, however in object we use keys without double quotes. This is the major difference between an object and a JSON. Let's see more examples about JSON.
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
{
|
||||
"Alex": {
|
||||
"email": "alex@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 30
|
||||
},
|
||||
"Asab": {
|
||||
"email": "asab@asab.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Redux",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 25,
|
||||
"isLoggedIn": false,
|
||||
"points": 50
|
||||
},
|
||||
"Brook": {
|
||||
"email": "daniel@daniel.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux"
|
||||
],
|
||||
"age": 30,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Daniel": {
|
||||
"email": "daniel@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Python"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"John": {
|
||||
"email": "john@john.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux",
|
||||
"Node.js"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Thomas": {
|
||||
"email": "thomas@thomas.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"Paul": {
|
||||
"email": "paul@paul.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Converting JSON to JavaScript Object
|
||||
|
||||
Mostly we fetch JSON data from HTTP response or from a file, but we can store the JSON as a string and we can change to Object for sake of demonstration. In JavaScript the keyword _JSON_ has _parse()_ and _stringify()_ methods. When we want to change the JSON to an object we parse the JSON using _JSON.parse()_. When we want to change the object to JSON we use _JSON.stringify()_.
|
||||
|
||||
#### JSON.parse()
|
||||
|
||||
```js
|
||||
JSON.parse(json[, reviver])
|
||||
// json or text , the data
|
||||
// reviver is an optional callback function
|
||||
/* JSON.parse(json, (key, value) => {
|
||||
|
||||
})
|
||||
*/
|
||||
```
|
||||
|
||||
```js
|
||||
const usersText = `{
|
||||
"users":[
|
||||
{
|
||||
"firstName":"Asabeneh",
|
||||
"lastName":"Yetayeh",
|
||||
"age":250,
|
||||
"email":"asab@asb.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Alex",
|
||||
"lastName":"James",
|
||||
"age":25,
|
||||
"email":"alex@alex.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Lidiya",
|
||||
"lastName":"Tekle",
|
||||
"age":28,
|
||||
"email":"lidiya@lidiya.com"
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
const usersObj = JSON.parse(usersText, undefined, 4)
|
||||
console.log(usersObj)
|
||||
```
|
||||
|
||||
### Using a reviver function with JSON.parse()
|
||||
|
||||
To use the reviver function as a formatter, we put the keys we want to format first name and last name value. Let us say, we are interested to format the firstName and lastName of the JSON data .
|
||||
|
||||
```js
|
||||
const usersText = `{
|
||||
"users":[
|
||||
{
|
||||
"firstName":"Asabeneh",
|
||||
"lastName":"Yetayeh",
|
||||
"age":250,
|
||||
"email":"asab@asb.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Alex",
|
||||
"lastName":"James",
|
||||
"age":25,
|
||||
"email":"alex@alex.com"
|
||||
},
|
||||
{
|
||||
"firstName":"Lidiya",
|
||||
"lastName":"Tekle",
|
||||
"age":28,
|
||||
"email":"lidiya@lidiya.com"
|
||||
}
|
||||
]
|
||||
}`
|
||||
|
||||
const usersObj = JSON.parse(usersText, (key, value) => {
|
||||
let newValue =
|
||||
typeof value == 'string' && key != 'email' ? value.toUpperCase() : value
|
||||
return newValue
|
||||
})
|
||||
console.log(usersObj)
|
||||
```
|
||||
|
||||
The _JSON.parse()_ is very handy to use. You do not have to pass optional parameter, you can just use it with the required parameter and you will achieve quite a lot.
|
||||
|
||||
### Converting Object to JSON
|
||||
|
||||
When we want to change the object to JSON we use _JSON.stringify()_. The stringify method takes one required parameter and two optional parameters. The replacer is used as filter and the space is an indentations. If we do not want to filter out any of the keys from the object we can just pass undefined.
|
||||
|
||||
```js
|
||||
JSON.stringify(obj, replacer, space)
|
||||
// json or text , the data
|
||||
// reviver is an optional callback function
|
||||
```
|
||||
|
||||
Let us convert the following object to a string. First let use keep all the keys and also let us have 4 space indentation.
|
||||
|
||||
```js
|
||||
const users = {
|
||||
Alex: {
|
||||
email: 'alex@alex.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 30
|
||||
},
|
||||
Asab: {
|
||||
email: 'asab@asab.com',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'Redux',
|
||||
'MongoDB',
|
||||
'Express',
|
||||
'React',
|
||||
'Node'
|
||||
],
|
||||
age: 25,
|
||||
isLoggedIn: false,
|
||||
points: 50
|
||||
},
|
||||
Brook: {
|
||||
email: 'daniel@daniel.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
|
||||
age: 30,
|
||||
isLoggedIn: true,
|
||||
points: 50
|
||||
},
|
||||
Daniel: {
|
||||
email: 'daniel@alex.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
},
|
||||
John: {
|
||||
email: 'john@john.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
|
||||
age: 20,
|
||||
isLoggedIn: true,
|
||||
points: 50
|
||||
},
|
||||
Thomas: {
|
||||
email: 'thomas@thomas.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React'],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
},
|
||||
Paul: {
|
||||
email: 'paul@paul.com',
|
||||
skills: [
|
||||
'HTML',
|
||||
'CSS',
|
||||
'JavaScript',
|
||||
'MongoDB',
|
||||
'Express',
|
||||
'React',
|
||||
'Node'
|
||||
],
|
||||
age: 20,
|
||||
isLoggedIn: false,
|
||||
points: 40
|
||||
}
|
||||
}
|
||||
|
||||
const txt = JSON.stringify(users, undefined, 4)
|
||||
console.log(txt) // text means JSON- because json is a string form of an object.
|
||||
```
|
||||
|
||||
```sh
|
||||
{
|
||||
"Alex": {
|
||||
"email": "alex@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 30
|
||||
},
|
||||
"Asab": {
|
||||
"email": "asab@asab.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Redux",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 25,
|
||||
"isLoggedIn": false,
|
||||
"points": 50
|
||||
},
|
||||
"Brook": {
|
||||
"email": "daniel@daniel.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux"
|
||||
],
|
||||
"age": 30,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Daniel": {
|
||||
"email": "daniel@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Python"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"John": {
|
||||
"email": "john@john.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux",
|
||||
"Node.js"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Thomas": {
|
||||
"email": "thomas@thomas.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"Paul": {
|
||||
"email": "paul@paul.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Using a Filter Array with JSON.stringify
|
||||
|
||||
Now, lets use the replacer as a filter. The user object has long list of keys but we are interested only in few of them. We put the keys we want to keep in array as show in the example and use it the place of the replacer.
|
||||
|
||||
```js
|
||||
const user = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
email: 'alex@alex.com',
|
||||
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Python'],
|
||||
age: 250,
|
||||
isLoggedIn: false,
|
||||
points: 30
|
||||
}
|
||||
|
||||
const txt = JSON.stringify(user,['firstName', 'lastName', 'country', 'city', 'age'],4)
|
||||
console.log(txt)
|
||||
```
|
||||
|
||||
```sh
|
||||
{
|
||||
"firstName": "Asabeneh",
|
||||
"lastName": "Yetayeh",
|
||||
"country": "Finland",
|
||||
"city": "Helsinki",
|
||||
"age": 250
|
||||
}
|
||||
```
|
||||
|
||||
🌕 You are extraordinary. Now, you knew a light-weight data format which you may use to store data or to send it an HTTP server. You are 16 steps a head to your way to greatness. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## Esercizi
|
||||
|
||||
```js
|
||||
const skills = ['HTML', 'CSS', 'JS', 'React','Node', 'Python']
|
||||
let age = 250;
|
||||
let isMarried = true
|
||||
const student = {
|
||||
firstName:'Asabeneh',
|
||||
lastName:'Yetayehe',
|
||||
age:250,
|
||||
isMarried:true,
|
||||
skills:['HTML', 'CSS', 'JS', 'React','Node', 'Python', ]
|
||||
}
|
||||
const txt = `{
|
||||
"Alex": {
|
||||
"email": "alex@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 30
|
||||
},
|
||||
"Asab": {
|
||||
"email": "asab@asab.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Redux",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 25,
|
||||
"isLoggedIn": false,
|
||||
"points": 50
|
||||
},
|
||||
"Brook": {
|
||||
"email": "daniel@daniel.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux"
|
||||
],
|
||||
"age": 30,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Daniel": {
|
||||
"email": "daniel@alex.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"Python"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"John": {
|
||||
"email": "john@john.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React",
|
||||
"Redux",
|
||||
"Node.js"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": true,
|
||||
"points": 50
|
||||
},
|
||||
"Thomas": {
|
||||
"email": "thomas@thomas.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"React"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
},
|
||||
"Paul": {
|
||||
"email": "paul@paul.com",
|
||||
"skills": [
|
||||
"HTML",
|
||||
"CSS",
|
||||
"JavaScript",
|
||||
"MongoDB",
|
||||
"Express",
|
||||
"React",
|
||||
"Node"
|
||||
],
|
||||
"age": 20,
|
||||
"isLoggedIn": false,
|
||||
"points": 40
|
||||
}
|
||||
}
|
||||
`
|
||||
```
|
||||
|
||||
### Esercizi Livello 1
|
||||
|
||||
1. Change skills array to JSON using JSON.stringify()
|
||||
1. Stringify the age variable
|
||||
1. Stringify the isMarried variable
|
||||
1. Stringify the student object
|
||||
|
||||
### Esercizi Livello 2
|
||||
|
||||
1. Stringify the students object with only firstName, lastName and skills properties
|
||||
|
||||
### Esercizi Livello 3
|
||||
|
||||
1. Parse the *txt* JSON to object.
|
||||
2. Find the user who has many skills from the variable stored in *txt*.
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 15](../15_Day_Classes/15_day_classes.md) | [Day 17 >>](../17_Day_Web_storages/17_day_web_storages.md)
|
@ -0,0 +1,104 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Closures</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 18](../18_Day_Promises/18_day_promises.md) | [Day 20 >>](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md)
|
||||
|
||||

|
||||
- [Day 19](#day-19)
|
||||
- [Closure](#closure)
|
||||
- [Esercizi](#exercises)
|
||||
- [Esercizi: Livello 1](#exercises-level-1)
|
||||
- [Esercizi: Livello 2](#exercises-level-2)
|
||||
- [Esercizi: Livello 3](#exercises-level-3)
|
||||
|
||||
# Day 19
|
||||
|
||||
## Closure
|
||||
|
||||
JavaScript allows writing function inside an outer function. We can write as many inner functions as we want. If inner function access the variables of outer function then it is called closure.
|
||||
|
||||
```js
|
||||
function outerFunction() {
|
||||
let count = 0;
|
||||
function innerFunction() {
|
||||
count++
|
||||
return count
|
||||
}
|
||||
|
||||
return innerFunction
|
||||
}
|
||||
const innerFunc = outerFunction()
|
||||
|
||||
console.log(innerFunc())
|
||||
console.log(innerFunc())
|
||||
console.log(innerFunc())
|
||||
```
|
||||
|
||||
```sh
|
||||
1
|
||||
2
|
||||
3
|
||||
```
|
||||
|
||||
Let us more example of inner functions
|
||||
|
||||
```js
|
||||
function outerFunction() {
|
||||
let count = 0;
|
||||
function plusOne() {
|
||||
count++
|
||||
return count
|
||||
}
|
||||
function minusOne() {
|
||||
count--
|
||||
return count
|
||||
}
|
||||
|
||||
return {
|
||||
plusOne:plusOne(),
|
||||
minusOne:minusOne()
|
||||
}
|
||||
}
|
||||
const innerFuncs = outerFunction()
|
||||
|
||||
console.log(innerFuncs.plusOne)
|
||||
console.log(innerFuncs.minusOne)
|
||||
```
|
||||
|
||||
```sh
|
||||
1
|
||||
0
|
||||
```
|
||||
|
||||
🌕 You are making progress. Maintain your momentum, keep the good work. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Esercizi: Livello 1
|
||||
|
||||
1. Create a closure which has one inner function
|
||||
|
||||
### Esercizi: Livello 2
|
||||
|
||||
1. Create a closure which has three inner functions
|
||||
|
||||
### Esercizi: Livello 3
|
||||
|
||||
1. Create a personAccount out function. It has firstname, lastname, incomes, expenses inner variables. It has totalIncome, totalExpense, accountInfo,addIncome, addExpense and accountBalance inner functions. Incomes is a set of incomes and its description and expenses is also a set of expenses and its description.
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 18](../18_Day_Promises/18_day_promises.md) | [Day 20 >>](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md)
|
@ -0,0 +1,360 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Writing Clean Codes</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 19](../19_Day_Closuers/19_day_closures.md) | [Day 21 >>](../21_Day_DOM/21_day_dom.md)
|
||||
|
||||

|
||||
- [Day 20](#day-20)
|
||||
- [Writing clean code](#writing-clean-code)
|
||||
- [JavaScript Style Guide](#javascript-style-guide)
|
||||
- [Why we need style guide](#why-we-need-style-guide)
|
||||
- [Airbnb JavaScript Style Guide](#airbnb-javascript-style-guide)
|
||||
- [Standard JavaScript Style Guide](#standard-javascript-style-guide)
|
||||
- [Google JavaScript Style Guide](#google-javascript-style-guide)
|
||||
- [JavaScript Coding Conventions](#javascript-coding-conventions)
|
||||
- [Conventions use in 30DaysOfJavaScript](#conventions-use-in-30daysofjavascript)
|
||||
- [Variables](#variables)
|
||||
- [Arrays](#arrays)
|
||||
- [Functions](#functions)
|
||||
- [Loops](#loops)
|
||||
- [Objects](#objects)
|
||||
- [Conditional](#conditional)
|
||||
- [Classes](#classes)
|
||||
|
||||
# Day 20
|
||||
|
||||
## Writing clean code
|
||||
|
||||
### JavaScript Style Guide
|
||||
|
||||
A JavaScript style guide is a set of standards that tells how JavaScript code should be written and organized. In this section, we will talk about JavaScript guides and how to write a clean code.
|
||||
|
||||
JavaScript is a programming language and like human language it has syntax. The syntax of JavaScript has to be written following a certain style guideline for sake of convince and simplicity.
|
||||
|
||||
### Why we need style guide
|
||||
|
||||
You have been coding alone for so long but now it seems to work in a team. It does not matter in anyway you write you code as long as it running, however when you work in team of 10 or 20 or more developer on one project and on the same code base, the code will be messy and hard to manage if there is no any guidelines to follow.
|
||||
|
||||
You can develop your own guidelines and conventions or you can also adapt well developed guidelines. Let us the most common know guidelines.
|
||||
Most common JavaScript Style Guides
|
||||
|
||||
- Airbnb JavaScript Style Guide
|
||||
- JavaScript Standard Style Guide
|
||||
- Google JavaScript Style Guide
|
||||
|
||||
#### Airbnb JavaScript Style Guide
|
||||
|
||||
Airbnb has one of the most popular JavaScript style guides on the internet. It covers nearly every aspect of JavaScript as well and it is adopted by many developer and companies. You may checkout the [Airbnb style guide](https://github.com/airbnb/javascript). I would also recommend to try it. Their style is very easy to use and simple to understand.
|
||||
|
||||
#### Standard JavaScript Style Guide
|
||||
|
||||
This is guideline is not as popular as Airbnb but it worth to look at it. They removed the semicolon in their [style guide](https://standardjs.com/).
|
||||
|
||||
#### Google JavaScript Style Guide
|
||||
|
||||
I do not say much about Googles guideline and I did not use rather I would suggest you to have a look from this [link](https://google.github.io/styleguide/jsguide.html).
|
||||
|
||||
### JavaScript Coding Conventions
|
||||
|
||||
In this challenge also we used the general JavaScript coding writing conventions and guides. Coding conventions are style guidelines for programming which are developed by an individual, a team or a company.
|
||||
|
||||
Coding conventions helps:
|
||||
|
||||
- to write clean code
|
||||
- to improve code readability
|
||||
- to improve code re-useability and maintainability
|
||||
|
||||
Coding conventions includes
|
||||
|
||||
- Naming and declaration rules for variables
|
||||
- Naming and declaration rules for functions
|
||||
- Rules for the use of white space, indentation, and comments
|
||||
- Programming practices and principles
|
||||
|
||||
#### Conventions use in 30DaysOfJavaScript
|
||||
|
||||
In this challenge we follow the regular JavaScript convention but I added also my preference of writing.
|
||||
|
||||
- We used camelCase for variables and functions.
|
||||
- All variable names start with a letter.
|
||||
- We chose to use *const* for constants, arrays, objects and functions. In stead of double quote, we chose to use single quote or backtick. Single quote is becoming trendy.
|
||||
- We also removed semicolons from our code but it is a matter of personal preference.
|
||||
- Space around arithmetic operators, assignment operators and after comma
|
||||
- Arrow function instead of function declaration
|
||||
- Explicit return instead of implicit return if the function is one liner
|
||||
- No trailing comma in the last value of an object
|
||||
- We prefer this +=, -=, *= /=, **= instead of the longer version
|
||||
- When we use console.log() it is good to print with a tag string to identify from where the console is coming
|
||||
|
||||
#### Variables
|
||||
|
||||
```js
|
||||
|
||||
let firstName = 'Asabeneh'
|
||||
let lastName = 'Yetayeh'
|
||||
let country = 'Finland'
|
||||
let city = 'Helsinki'
|
||||
|
||||
const PI = Math.PI
|
||||
const gravity = 9.81
|
||||
```
|
||||
|
||||
#### Arrays
|
||||
|
||||
We chose to make array names plural
|
||||
|
||||
- names
|
||||
- numbers
|
||||
- countries
|
||||
- languages
|
||||
- skills
|
||||
- fruits
|
||||
- vegetables
|
||||
|
||||
```js
|
||||
// arrays
|
||||
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
|
||||
const numbers = [0, 3.14, 9.81, 37, 98.6, 100]
|
||||
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland']
|
||||
const languages = ['Amharic', 'Arabic', 'English', 'French', 'Spanish']
|
||||
const skills = ['HTML', 'CSS', 'JavaScript', 'React', 'Python']
|
||||
const fruits = ['banana', 'orange', 'mango', 'lemon']
|
||||
const vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot']
|
||||
```
|
||||
|
||||
#### Functions
|
||||
|
||||
By now you are very familiar function declaration, expression function, arrow function and anonymous function. In this challenge we tend to use arrow function instead of other functions. Arrow function is not a replacement for other functions. In addition, arrow functions and function declarations are not exactly the same. So you should know when to use and when not. I will cover the difference in detail in other sections. We will use explicit return instead of implicit return if the function is one liner
|
||||
|
||||
```js
|
||||
// function which return full name of a person
|
||||
const printFullName = (firstName, lastName) => firstName + ' ' + lastName
|
||||
|
||||
// function which calculates a square of a number
|
||||
const square = (n) => n * n
|
||||
|
||||
// a function which generate random hexa colors
|
||||
const hexaColor = () => {
|
||||
const str = '0123456789abcdef'
|
||||
let hexa = '#'
|
||||
let index
|
||||
for (let i = 0; i < 6; i++) {
|
||||
index = Math.floor(Math.random() * str.length)
|
||||
hexa += str[index]
|
||||
}
|
||||
return hexa
|
||||
}
|
||||
|
||||
// a function which shows date and time
|
||||
const showDateTime = () => {
|
||||
const now = new Date()
|
||||
const year = now.getFullYear()
|
||||
const month = now.getMonth() + 1
|
||||
const date = now.getDate()
|
||||
let hours = now.getHours()
|
||||
let minutes = now.getMinutes()
|
||||
if (hours < 10) {
|
||||
hours = '0' + hours
|
||||
}
|
||||
if (minutes < 10) {
|
||||
minutes = '0' + minutes
|
||||
}
|
||||
|
||||
const dateMonthYear = date + '.' + month + '.' + year
|
||||
const time = hours + ':' + minutes
|
||||
const fullTime = dateMonthYear + ' ' + time
|
||||
return fullTime
|
||||
}
|
||||
```
|
||||
|
||||
The `new Dat().toLocaleString()` can also be used to display current date time. The `toLocaleString()` methods takes different arguments. You may learn more about date and time from this [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString).
|
||||
|
||||
#### Loops
|
||||
|
||||
We coverer many types of loops in this challenges. The regular for loop, while loop, do while loop, for of loop, forEach loop and for in loop.
|
||||
Lets see how we use them:
|
||||
|
||||
```js
|
||||
for (let i = 0; i < n; i++){
|
||||
console.log()
|
||||
}
|
||||
|
||||
// declaring an array variable
|
||||
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
|
||||
|
||||
// iterating an array using regular for loop
|
||||
let len = names.length;
|
||||
for(let i = 0; i < len; i++){
|
||||
console.log(names[i].toUpperCase())
|
||||
}
|
||||
|
||||
|
||||
// iterating an array using for of
|
||||
for( const name of names) {
|
||||
console.log(name.toUpperCase())
|
||||
}
|
||||
|
||||
// iterating array using forEach
|
||||
names.forEach((name) => name.toUpperCase())
|
||||
|
||||
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: ['HTML','CSS','JavaScript','React','Node','MongoDB','Python','D3.js'],
|
||||
isMarried: true
|
||||
}
|
||||
for(const key in person) {
|
||||
console.log(key)
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
#### Objects
|
||||
|
||||
We declare object literal with *const*.
|
||||
|
||||
```js
|
||||
// declaring object literal
|
||||
const person = {
|
||||
firstName: 'Asabeneh',
|
||||
lastName: 'Yetayeh',
|
||||
age: 250,
|
||||
country: 'Finland',
|
||||
city: 'Helsinki',
|
||||
skills: ['HTML','CSS','JavaScript','TypeScript', 'React','Node','MongoDB','Python','D3.js'],
|
||||
isMarried: true
|
||||
}
|
||||
// iterating through object keys
|
||||
for(const key in person) {
|
||||
console.log(key, person[key])
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
#### Conditional
|
||||
|
||||
We say if, if else, if else if else, switch and ternary operators in previous challenges.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
if (condition) {
|
||||
// this part of code run for truthy condition
|
||||
} else {
|
||||
// this part of code run for false condition
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// if else
|
||||
let num = 3
|
||||
if (num > 0) {
|
||||
console.log(`${num} is a positive number`)
|
||||
} else {
|
||||
console.log(`${num} is a negative number`)
|
||||
}
|
||||
// 3 is a positive number
|
||||
```
|
||||
|
||||
```js
|
||||
// if else if else if else
|
||||
|
||||
let a = 0
|
||||
if (a > 0) {
|
||||
console.log(`${a} is a positive number`)
|
||||
} else if (a < 0) {
|
||||
console.log(`${a} is a negative number`)
|
||||
} else if (a == 0) {
|
||||
console.log(`${a} is zero`)
|
||||
} else {
|
||||
console.log(`${a} is not a number`)
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// Switch More Examples
|
||||
let dayUserInput = prompt('What day is today ?')
|
||||
let day = dayUserInput.toLowerCase()
|
||||
|
||||
switch (day) {
|
||||
case 'monday':
|
||||
console.log('Today is Monday')
|
||||
break
|
||||
case 'tuesday':
|
||||
console.log('Today is Tuesday')
|
||||
break
|
||||
case 'wednesday':
|
||||
console.log('Today is Wednesday')
|
||||
break
|
||||
case 'thursday':
|
||||
console.log('Today is Thursday')
|
||||
break
|
||||
case 'friday':
|
||||
console.log('Today is Friday')
|
||||
break
|
||||
case 'saturday':
|
||||
console.log('Today is Saturday')
|
||||
break
|
||||
case 'sunday':
|
||||
console.log('Today is Sunday')
|
||||
break
|
||||
default:
|
||||
console.log('It is not a week day.')
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// ternary
|
||||
|
||||
let isRaining = true
|
||||
isRaining
|
||||
? console.log('You need a rain coat.')
|
||||
: console.log('No need for a rain coat.')
|
||||
```
|
||||
|
||||
#### Classes
|
||||
|
||||
We declare class with CamelCase which starts with capital letter.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
class ClassName {
|
||||
// code goes here
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
// defining class
|
||||
class Person {
|
||||
constructor(firstName, lastName) {
|
||||
console.log(this) // Check the output from here
|
||||
this.firstName = firstName
|
||||
this.lastName = lastName
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Whatever style guide you follow be consistent. Follow some programming paradigms and design patterns. Remember, if you do not write you code in certain order or fashion it will be hard to read your code. So, do a favor for yourself or for someone who is going to read your code by writing readable code.
|
||||
|
||||
🌕 You are tidy. Now, you knew how to write clean code, so anyone who know the English language can understand your code. You are always progressing and you are a head of 20 steps to your way to greatness.
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 19](../19_Day_Closuers/19_day_closures.md) | [Day 21 >>](../21_Day_DOM/21_day_dom.md)
|
@ -0,0 +1,409 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Document Object Model(DOM)</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 20](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) | [Day 22 >>](../22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md)
|
||||
|
||||

|
||||
|
||||
- [Day 21](#day-21)
|
||||
- [Document Object Model (DOM) - Day 1](#document-object-model-dom---day-1)
|
||||
- [Getting Element](#getting-element)
|
||||
- [Getting elements by tag name](#getting-elements-by-tag-name)
|
||||
- [Getting elements by class name](#getting-elements-by-class-name)
|
||||
- [Getting an element by id](#getting-an-element-by-id)
|
||||
- [Getting elements by using querySelector methods](#getting-elements-by-using-queryselector-methods)
|
||||
- [Adding attribute](#adding-attribute)
|
||||
- [Adding attribute using setAttribute](#adding-attribute-using-setattribute)
|
||||
- [Adding attribute without setAttribute](#adding-attribute-without-setattribute)
|
||||
- [Adding class using classList](#adding-class-using-classlist)
|
||||
- [Removing class using remove](#removing-class-using-remove)
|
||||
- [Adding Text to HTML element](#adding-text-to-html-element)
|
||||
- [Adding Text content using textContent](#adding-text-content-using-textcontent)
|
||||
- [Adding Text Content using innerHTML](#adding-text-content-using-innerhtml)
|
||||
- [Text Content](#text-content)
|
||||
- [Inner HTML](#inner-html)
|
||||
- [Adding style](#adding-style)
|
||||
- [Adding Style Color](#adding-style-color)
|
||||
- [Adding Style Background Color](#adding-style-background-color)
|
||||
- [Adding Style Font Size](#adding-style-font-size)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
- [Exercise: Livello 2](#exercise-level-2)
|
||||
- [Exercise: Livello 3](#exercise-level-3)
|
||||
- [DOM: Mini project 1](#dom-mini-project-1)
|
||||
|
||||
# Day 21
|
||||
|
||||
## Document Object Model (DOM) - Day 1
|
||||
|
||||
HTML document is structured as a JavaScript Object. Every HTML element has a different properties which can help to manipulate it. It is possible to get, create, append or remove HTML elements using JavaScript. Check the examples below. Selecting HTML element using JavaScript is similar to selecting using CSS. To select an HTML element, we use tag name, id, class name or other attributes.
|
||||
|
||||
### Getting Element
|
||||
|
||||
We can access already created element or elements using JavaScript. To access or get elements we use different methods. The code below has four _h1_ elements. Let us see the different methods to access the _h1_ elements.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1 class='title' id='first-title'>First Title</h1>
|
||||
<h1 class='title' id='second-title'>Second Title</h1>
|
||||
<h1 class='title' id='third-title'>Third Title</h1>
|
||||
<h1></h1>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### Getting elements by tag name
|
||||
|
||||
**_getElementsByTagName()_**:takes a tag name as a string parameter and this method returns an HTMLCollection object. An HTMLCollection is an array like object of HTML elements. The length property provides the size of the collection. Whenever we use this method we access the individual elements using index or after loop through each individual items. An HTMLCollection does not support all array methods therefore we should use regular for loop instead of forEach.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
document.getElementsByTagName('tagname')
|
||||
```
|
||||
|
||||
```js
|
||||
const allTitles = document.getElementsByTagName('h1')
|
||||
|
||||
console.log(allTitles) //HTMLCollections
|
||||
console.log(allTitles.length) // 4
|
||||
|
||||
for (let i = 0; i < allTitles.length; i++) {
|
||||
console.log(allTitles[i]) // prints each elements in the HTMLCollection
|
||||
}
|
||||
```
|
||||
|
||||
#### Getting elements by class name
|
||||
|
||||
**_getElementsByClassName()_** method returns an HTMLCollection object. An HTMLCollection is an array like list of HTML elements. The length property provides the size of the collection. It is possible to loop through all the HTMLCollection elements. See the example below
|
||||
|
||||
```js
|
||||
//syntax
|
||||
document.getElementsByClassName('classname')
|
||||
```
|
||||
|
||||
```js
|
||||
const allTitles = document.getElementsByClassName('title')
|
||||
|
||||
console.log(allTitles) //HTMLCollections
|
||||
console.log(allTitles.length) // 4
|
||||
|
||||
for (let i = 0; i < allTitles.length; i++) {
|
||||
console.log(allTitles[i]) // prints each elements in the HTMLCollection
|
||||
}
|
||||
```
|
||||
|
||||
#### Getting an element by id
|
||||
|
||||
**_getElementsById()_** targets a single HTML element. We pass the id without # as an argument.
|
||||
|
||||
```js
|
||||
//syntax
|
||||
document.getElementById('id')
|
||||
```
|
||||
|
||||
```js
|
||||
let firstTitle = document.getElementById('first-title')
|
||||
console.log(firstTitle) // <h1>First Title</h1>
|
||||
```
|
||||
|
||||
#### Getting elements by using querySelector methods
|
||||
|
||||
The _document.querySelector_ method can select an HTML or HTML elements by tag name, by id or by class name.
|
||||
|
||||
**_querySelector_**: can be used to select HTML element by its tag name, id or class. If the tag name is used it selects only the first element.
|
||||
|
||||
```js
|
||||
let firstTitle = document.querySelector('h1') // select the first available h1 element
|
||||
let firstTitle = document.querySelector('#first-title') // select id with first-title
|
||||
let firstTitle = document.querySelector('.title') // select the first available element with class title
|
||||
```
|
||||
|
||||
**_querySelectorAll_**: can be used to select html elements by its tag name or class. It returns a nodeList which is an array like object which supports array methods. We can use **_for loop_** or **_forEach_** to loop through each nodeList elements.
|
||||
|
||||
```js
|
||||
const allTitles = document.querySelectorAll('h1') # selects all the available h1 elements in the page
|
||||
|
||||
console.log(allTitles.length) // 4
|
||||
for (let i = 0; i < allTitles.length; i++) {
|
||||
console.log(allTitles[i])
|
||||
}
|
||||
|
||||
allTitles.forEach(title => console.log(title))
|
||||
const allTitles = document.querySelectorAll('.title') // the same goes for selecting using class
|
||||
```
|
||||
|
||||
### Adding attribute
|
||||
|
||||
An attribute is added in the opening tag of HTML which gives additional information about the element. Common HTML attributes: id, class, src, style, href,disabled, title, alt. Lets add id and class for the fourth title.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll('h1')
|
||||
titles[3].className = 'title'
|
||||
titles[3].id = 'fourth-title'
|
||||
```
|
||||
|
||||
#### Adding attribute using setAttribute
|
||||
|
||||
The **_setAttribute()_** method set any html attribute. It takes two parameters the type of the attribute and the name of the attribute.
|
||||
Let's add class and id attribute for the fourth title.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll('h1')
|
||||
titles[3].setAttribute('class', 'title')
|
||||
titles[3].setAttribute('id', 'fourth-title')
|
||||
```
|
||||
|
||||
#### Adding attribute without setAttribute
|
||||
|
||||
We can use normal object setting method to set an attribute but this can not work for all elements. Some attributes are DOM object property and they can be set directly. For instance id and class
|
||||
|
||||
```js
|
||||
//another way to setting an attribute
|
||||
titles[3].className = 'title'
|
||||
titles[3].id = 'fourth-title'
|
||||
```
|
||||
|
||||
#### Adding class using classList
|
||||
|
||||
The class list method is a good method to append additional class. It does not override the original class if a class exists rather it adds additional class for the element.
|
||||
|
||||
```js
|
||||
//another way to setting an attribute: append the class, doesn't over ride
|
||||
titles[3].classList.add('title', 'header-title')
|
||||
```
|
||||
|
||||
#### Removing class using remove
|
||||
|
||||
Similar to adding we can also remove class from an element. We can remove a specific class from an element.
|
||||
|
||||
```js
|
||||
//another way to setting an attribute: append the class, doesn't over ride
|
||||
titles[3].classList.remove('title', 'header-title')
|
||||
```
|
||||
|
||||
### Adding Text to HTML element
|
||||
|
||||
An HTML is a build block of an opening tag, a closing tag and a text content. We can add a text content using the property _textContent_ or \*innerHTML.
|
||||
|
||||
#### Adding Text content using textContent
|
||||
|
||||
The _textContent_ property is used to add text to an HTML element.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll('h1')
|
||||
titles[3].textContent = 'Fourth Title'
|
||||
```
|
||||
|
||||
#### Adding Text Content using innerHTML
|
||||
|
||||
Most people get confused between _textContent_ and _innerHTML_. _textContent_ is meant to add text to an HTML element, however innerHTML can add a text or HTML element or elements as a child.
|
||||
|
||||
##### Text Content
|
||||
|
||||
We assign *textContent* HTML object property to a text
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll('h1')
|
||||
titles[3].textContent = 'Fourth Title'
|
||||
```
|
||||
|
||||
##### Inner HTML
|
||||
|
||||
We use innerHTML property when we like to replace or a completely new children content to a parent element.
|
||||
It value we assign is going to be a string of HTML elements.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>JavaScript for Everyone:DOM</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrapper">
|
||||
<h1>Asabeneh Yetayeh challenges in 2020</h1>
|
||||
<h2>30DaysOfJavaScript Challenge</h2>
|
||||
<ul></ul>
|
||||
</div>
|
||||
<script>
|
||||
const lists = `
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Ongoing</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>`
|
||||
const ul = document.querySelector('ul')
|
||||
ul.innerHTML = lists
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
The innerHTML property can allow us also to remove all the children of a parent element. Instead of using removeChild() I would recommend the following method.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>JavaScript for Everyone:DOM</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrapper">
|
||||
<h1>Asabeneh Yetayeh challenges in 2020</h1>
|
||||
<h2>30DaysOfJavaScript Challenge</h2>
|
||||
<ul>
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Ongoing</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>
|
||||
</ul>
|
||||
</div>
|
||||
<script>
|
||||
const ul = document.querySelector('ul')
|
||||
ul.innerHTML = ''
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Adding style
|
||||
|
||||
#### Adding Style Color
|
||||
|
||||
Let us add some style to our titles. If the element has even index we give it green color else red.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll('h1')
|
||||
titles.forEach((title, i) => {
|
||||
title.style.fontSize = '24px' // all titles will have 24px font size
|
||||
if (i % 2 === 0) {
|
||||
title.style.color = 'green'
|
||||
} else {
|
||||
title.style.color = 'red'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
#### Adding Style Background Color
|
||||
|
||||
Let us add some style to our titles. If the element has even index we give it green color else red.
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll('h1')
|
||||
titles.forEach((title, i) => {
|
||||
title.style.fontSize = '24px' // all titles will have 24px font size
|
||||
if (i % 2 === 0) {
|
||||
title.style.backgroundColor = 'green'
|
||||
} else {
|
||||
title.style.backgroundColor = 'red'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
#### Adding Style Font Size
|
||||
|
||||
Let us add some style to our titles. If the element has even index we give it 20px else 30px
|
||||
|
||||
```js
|
||||
const titles = document.querySelectorAll('h1')
|
||||
titles.forEach((title, i) => {
|
||||
title.style.fontSize = '24px' // all titles will have 24px font size
|
||||
if (i % 2 === 0) {
|
||||
title.style.fontSize = '20px'
|
||||
} else {
|
||||
title.style.fontSize = '30px'
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
As you have notice, the properties of css when we use it in JavaScript is going to be a camelCase. The following CSS properties change from background-color to backgroundColor, font-size to fontSize, font-family to fontFamily, margin-bottom to marginBottom.
|
||||
|
||||
---
|
||||
|
||||
🌕 Now, you are fully charged with a super power, you have completed the most important and challenging part of the challenge and in general JavaScript. You learned DOM and now you have the capability to build and develop applications. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Create an index.html file and put four p elements as above: Get the first paragraph by using **_document.querySelector(tagname)_** and tag name
|
||||
2. Get each of the the paragraph using **_document.querySelector('#id')_** and by their id
|
||||
3. Get all the p as nodeList using **_document.querySelectorAll(tagname)_** and by their tag name
|
||||
4. Loop through the nodeList and get the text content of each paragraph
|
||||
5. Set a text content to paragraph the fourth paragraph,**_Fourth Paragraph_**
|
||||
6. Set id and class attribute for all the paragraphs using different attribute setting methods
|
||||
|
||||
### Exercise: Livello 2
|
||||
|
||||
1. Change stye of each paragraph using JavaScript(eg. color, background, border, font-size, font-family)
|
||||
1. Select all paragraphs and loop through each elements and give the first and third paragraph a color of green, and the second and the fourth paragraph a red color
|
||||
1. Set text content, id and class to each paragraph
|
||||
|
||||
### Exercise: Livello 3
|
||||
|
||||
#### DOM: Mini project 1
|
||||
|
||||
1. Develop the following application, use the following HTML elements to get started with. You will get the same code on starter folder. Apply all the styles and functionality using JavaScript only.
|
||||
|
||||
- The year color is changing every 1 second
|
||||
- The date and time background color is changing every on seconds
|
||||
- Completed challenge has background green
|
||||
- Ongoing challenge has background yellow
|
||||
- Coming challenges have background red
|
||||
|
||||
```html
|
||||
<!-- index.html -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>JavaScript for Everyone:DOM</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrapper">
|
||||
<h1>Asabeneh Yetayeh challenges in 2020</h1>
|
||||
<h2>30DaysOfJavaScript Challenge</h2>
|
||||
<ul>
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Ongoing</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>
|
||||
</ul>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 20](../20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) | [Day 22 >>](../22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md)
|
@ -0,0 +1,231 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Manipulating DOM Object</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 21](../21_Day_DOM/21_day_dom.md) | [Day 23 >>](../23_Day_Event_listeners/23_day_event_listeners.md)
|
||||
|
||||

|
||||
- [Day 22](#day-22)
|
||||
- [DOM(Document Object Model)-Day 2](#domdocument-object-model-day-2)
|
||||
- [Creating an Element](#creating-an-element)
|
||||
- [Creating elements](#creating-elements)
|
||||
- [Appending child to a parent element](#appending-child-to-a-parent-element)
|
||||
- [Removing a child element from a parent node](#removing-a-child-element-from-a-parent-node)
|
||||
- [Esercizi](#exercises)
|
||||
- [Esercizi: Livello 1](#exercises-level-1)
|
||||
- [Esercizi: Livello 2](#exercises-level-2)
|
||||
- [Esercizi: Livello 3](#exercises-level-3)
|
||||
|
||||
# Day 22
|
||||
|
||||
## DOM(Document Object Model)-Day 2
|
||||
|
||||
### Creating an Element
|
||||
|
||||
To create an HTML element we use tag name. Creating an HTML element using JavaScript is very simple and straight forward. We use the method _document.createElement()_. The method takes an HTML element tag name as a string parameter.
|
||||
|
||||
```js
|
||||
// syntax
|
||||
document.createElement('tagname')
|
||||
```
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<script>
|
||||
let title = document.createElement('h1')
|
||||
title.className = 'title'
|
||||
title.style.fontSize = '24px'
|
||||
title.textContent = 'Creating HTML element DOM Day 2'
|
||||
|
||||
console.log(title)
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
### Creating elements
|
||||
|
||||
To create multiple elements we should use loop. Using loop we can create as many HTML elements as we want.
|
||||
After we create the element we can assign value to the different properties of the HTML object.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<script>
|
||||
let title
|
||||
for (let i = 0; i < 3; i++) {
|
||||
title = document.createElement('h1')
|
||||
title.className = 'title'
|
||||
title.style.fontSize = '24px'
|
||||
title.textContent = i
|
||||
console.log(title)
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
### Appending child to a parent element
|
||||
|
||||
To see a created element on the HTML document we should append it to the parent as a child element. We can access the HTML document body using *document.body*. The *document.body* support the *appendChild()* method. See the example below.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<script>
|
||||
// creating multiple elements and appending to parent element
|
||||
let title
|
||||
for (let i = 0; i < 3; i++) {
|
||||
title = document.createElement('h1')
|
||||
title.className = 'title'
|
||||
title.style.fontSize = '24px'
|
||||
title.textContent = i
|
||||
document.body.appendChild(title)
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Removing a child element from a parent node
|
||||
|
||||
After creating an HTML, we may want to remove element or elements and we can use the *removeChild()* method.
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Removing child Node</h1>
|
||||
<h2>Asabeneh Yetayeh challenges in 2020</h1>
|
||||
<ul>
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Done</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>
|
||||
</ul>
|
||||
|
||||
<script>
|
||||
const ul = document.querySelector('ul')
|
||||
const lists = document.querySelectorAll('li')
|
||||
for (const list of lists) {
|
||||
ul.removeChild(list)
|
||||
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
As we have see in the previous section there is a better way to eliminate all the inner HTML elements or the children of a parent element using the method *innerHTML* properties.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Removing child Node</h1>
|
||||
<h2>Asabeneh Yetayeh challenges in 2020</h1>
|
||||
<ul>
|
||||
<li>30DaysOfPython Challenge Done</li>
|
||||
<li>30DaysOfJavaScript Challenge Done</li>
|
||||
<li>30DaysOfReact Challenge Coming</li>
|
||||
<li>30DaysOfFullStack Challenge Coming</li>
|
||||
<li>30DaysOfDataAnalysis Challenge Coming</li>
|
||||
<li>30DaysOfReactNative Challenge Coming</li>
|
||||
<li>30DaysOfMachineLearning Challenge Coming</li>
|
||||
</ul>
|
||||
|
||||
<script>
|
||||
const ul = document.querySelector('ul')
|
||||
ul.innerHTML = ''
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
The above snippet of code cleared all the child elements.
|
||||
|
||||
---
|
||||
|
||||
🌕 You are so special, you are progressing everyday. Now, you knew how to destroy a created DOM element when it is needed. You learned DOM and now you have the capability to build and develop applications. You are left with only eight days to your way to greatness. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Esercizi: Livello 1
|
||||
|
||||
1. Create a div container on HTML document and create 100 to 100 numbers dynamically and append to the container div.
|
||||
- Even numbers background is green
|
||||
- Odd numbers background is yellow
|
||||
- Prime numbers background is red
|
||||
|
||||

|
||||
|
||||
### Esercizi: Livello 2
|
||||
|
||||
1. Use the countries array to display all the countries.See the design
|
||||
|
||||

|
||||
|
||||
### Esercizi: Livello 3
|
||||
|
||||
Check the requirement of this project from both images(jpg and gif). All the data and CSS has been implemented using JavaScript only. The data is found on starter folder project_3. The drop down button has been created using [*details*](https://www.w3schools.com/tags/tag_details.asp) HTML element.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 21](../21_Day_DOM/21_day_dom.md) | [Day 23 >>](../23_Day_Event_listeners/23_day_event_listeners.md)
|
@ -0,0 +1,332 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Event Listeners</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 22](../22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) | [Day 24 >>](../24_Day_Project_solar_system/24_day_project_solar_system.md)
|
||||
|
||||

|
||||
|
||||
- [Day 22](#day-22)
|
||||
- [DOM(Document Object Model)-Day 3](#domdocument-object-model-day-3)
|
||||
- [Event Listeners](#event-listeners)
|
||||
- [Click](#click)
|
||||
- [Double Click](#double-click)
|
||||
- [Mouse enter](#mouse-enter)
|
||||
- [Getting value from an input element](#getting-value-from-an-input-element)
|
||||
- [input value](#input-value)
|
||||
- [input event and change](#input-event-and-change)
|
||||
- [blur event](#blur-event)
|
||||
- [keypress, keydow and keyup](#keypress-keydow-and-keyup)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
|
||||
# Day 22
|
||||
|
||||
## DOM(Document Object Model)-Day 3
|
||||
|
||||
### Event Listeners
|
||||
|
||||
Common HTML events:onclick, onchange, onmouseover, onmouseout, onkeydown, onkeyup, onload.
|
||||
We can add event listener method to any DOM object. We use **_addEventListener()_** method to listen different event types on HTML elements. The _addEventListener()_ method takes two arguments, an event listener and a callback function.
|
||||
|
||||
```js
|
||||
selectedElement.addEventListener('eventlistner', function(e) {
|
||||
// the activity you want to occur after the event will be in here
|
||||
})
|
||||
// or
|
||||
|
||||
selectedElement.addEventListener('eventlistner', e => {
|
||||
// the activity you want to occur after the event will be in here
|
||||
})
|
||||
```
|
||||
|
||||
#### Click
|
||||
|
||||
To attach an event listener to an element, first we select the element then we attach the addEventListener method. The event listener takes event type and callback functions as argument.
|
||||
|
||||
The following is an example of click type event.
|
||||
|
||||
**Esempio: click**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button>Click Me</button>
|
||||
|
||||
<script>
|
||||
const button = document.querySelector('button')
|
||||
button.addEventListener('click', e => {
|
||||
console.log('e gives the event listener object:', e)
|
||||
console.log('e.target gives the selected element: ', e.target)
|
||||
console.log(
|
||||
'e.target.textContent gives content of selected element: ',
|
||||
e.target.textContent
|
||||
)
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
An event can be also attached directly to the HTML element as inline script.
|
||||
|
||||
**Esempio: onclick**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button onclick="clickMe()">Click Me</button>
|
||||
<script>
|
||||
const clickMe = () => {
|
||||
alert('We can attach event on HTML element')
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### Double Click
|
||||
|
||||
To attach an event listener to an element, first we select the element then we attach the addEventListener method. The event listener takes event type and callback functions as argument.
|
||||
|
||||
The following is an example of click type event.
|
||||
**Esempio: dblclick**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button>Click Me</button>
|
||||
<script>
|
||||
const button = document.querySelector('button')
|
||||
button.addEventListener('dblclick', e => {
|
||||
console.log('e gives the event listener object:', e)
|
||||
console.log('e.target gives the selected element: ', e.target)
|
||||
console.log(
|
||||
'e.target.textContent gives content of selected element: ',
|
||||
e.target.textContent
|
||||
)
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### Mouse enter
|
||||
|
||||
To attach an event listener to an element, first we select the element then we attach the addEventListener method. The event listener takes event type and callback functions as argument.
|
||||
|
||||
The following is an example of click type event.
|
||||
|
||||
**Esempio: mouseenter**
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button>Click Me</button>
|
||||
<script>
|
||||
const button = document.querySelector('button')
|
||||
button.addEventListener('mouseenter', e => {
|
||||
console.log('e gives the event listener object:', e)
|
||||
console.log('e.target gives the selected element: ', e.target)
|
||||
console.log(
|
||||
'e.target.textContent gives content of selected element: ',
|
||||
e.target.textContent
|
||||
)
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
By now you are familiar with addEventListen method and how to attach event listener. There are many types of event listeners. But in this challenge we will focus the most common important events.
|
||||
List of events:
|
||||
|
||||
- click - when the element clicked
|
||||
- dblclick - when the element double clicked
|
||||
- mouseenter - when the mouse point enter to the element
|
||||
- mouseleave - when the mouse pointer leave the element
|
||||
- mousemove - when the mouse pointer move on the element
|
||||
- mouseover - when the mouse pointer move on the element
|
||||
- mouseout -when the mouse pointer out from the element
|
||||
- input -when value enter to input field
|
||||
- change -when value change on input field
|
||||
- blur -when the element is not focused
|
||||
- keydown - when a key is down
|
||||
- keyup - when a key is up
|
||||
- keypress - when we press any key
|
||||
- onload - when the browser has finished loading a page
|
||||
|
||||
Test the above event types by replacing event type in the above snippet code.
|
||||
|
||||
### Getting value from an input element
|
||||
|
||||
We usually fill forms and forms accept data. Form fields are created using input HTML element. Let us build a small application which allow us to calculate body mas index of a person using two input fields, one button and one p tag.
|
||||
|
||||
### input value
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Body Mass Index Calculator</h1>
|
||||
|
||||
<input type="text" id="mass" placeholder="Mass in Kilogram" />
|
||||
<input type="text" id="height" placeholder="Height in meters" />
|
||||
<button>Calculate BMI</button>
|
||||
|
||||
<script>
|
||||
const mass = document.querySelector('#mass')
|
||||
const height = document.querySelector('#height')
|
||||
const button = document.querySelector('button')
|
||||
|
||||
let bmi
|
||||
button.addEventListener('click', () => {
|
||||
bmi = mass.value / height.value ** 2
|
||||
alert(`your bmi is ${bmi.toFixed(2)}`)
|
||||
console.log(bmi)
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### input event and change
|
||||
|
||||
In the above example, we managed to get input values from two input fields by clicking button. How about if we want to get value without click the button. We can use the _change_ or _input_ event type to get data right away from the input field when the field is on focus. Let us see how we will handle that.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Data Binding using input or change event</h1>
|
||||
|
||||
<input type="text" placeholder="say something" />
|
||||
<p></p>
|
||||
|
||||
<script>
|
||||
const input = document.querySelector('input')
|
||||
const p = document.querySelector('p')
|
||||
|
||||
input.addEventListener('input', e => {
|
||||
p.textContent = e.target.value
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
#### blur event
|
||||
|
||||
In contrast to _input_ or _change_, the _blur_ event occur when the input field is not on focus.
|
||||
|
||||
```js
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Giving feedback using blur event</h1>
|
||||
|
||||
<input type="text" id="mass" placeholder="say something" />
|
||||
<p></p>
|
||||
|
||||
<script>
|
||||
const input = document.querySelector('input')
|
||||
const p = document.querySelector('p')
|
||||
|
||||
input.addEventListener('blur', (e) => {
|
||||
p.textContent = 'Field is required'
|
||||
p.style.color = 'red'
|
||||
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
```
|
||||
|
||||
#### keypress, keydow and keyup
|
||||
|
||||
We can access all the key numbers of the keyboard using different event listener types. Let us use keypress and get the keyCode of each keyboard keys.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document Object Model:30 Days Of JavaScript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Key events: Press any key</h1>
|
||||
|
||||
<script>
|
||||
document.body.addEventListener('keypress', e => {
|
||||
alert(e.keyCode)
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
🌕 You are so special, you are progressing everyday. Now, you knew how handle any kind of DOM events. . You are left with only seven days to your way to greatness. Now do some exercises for your brain and for your muscle.
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Generating numbers and marking evens, odds and prime numbers with three different colors. See the image below.
|
||||
|
||||

|
||||
|
||||
1. Generating the keyboard code code using even listener. The image below.
|
||||
|
||||

|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 22](../22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) | [Day 24 >>](../24_Day_Project_solar_system/24_day_project_solar_system.md)
|
@ -0,0 +1,38 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Mini Project Solar System</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 23](../23_Day_Event_listeners/23_day_event_listeners.md) | [Day 25 >>](../25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md)
|
||||
|
||||

|
||||
|
||||
- [Day 24](#day-24)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
|
||||
# Day 24
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Develop a small application which calculate a weight of an object in a certain planet. The gif image is not complete check the video in the starter file.
|
||||
|
||||

|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 23](../23_Day_Event_listeners/23_day_event_listeners.md) | [Day 25 >>](../25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md)
|
||||
|
@ -0,0 +1,39 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: World Countries Data Visualization</h1>
|
||||
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
|
||||
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
|
||||
</a>
|
||||
<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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 24](../24_Day_Project_solar_system/24_day_project_solar_system.md) | [Day 26 >>](../26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md)
|
||||
|
||||

|
||||
|
||||
- [Day 25](#day-25)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
|
||||
# Day 25
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Visualize the ten most populated countries and the ten most spoken languages in the world using DOM(HTML, CSS, JS)
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 24](../24_Day_Project_soloar_system/24_day_project_soloar_system.md) | [Day 26 >>](../26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md)
|
@ -0,0 +1,37 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: World Countries Data Visualization 2 </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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 25](../25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) | [Day 27 >>](../27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md)
|
||||
|
||||

|
||||
|
||||
- [Day 26](#day-26)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
|
||||
# Day 26
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Visualize the countries array as follows
|
||||
|
||||

|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 25](../25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) | [Day 27 >>](../27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md)
|
@ -0,0 +1,37 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Portfolio</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 26](../26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) | [Day 28 >>](../28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md)
|
||||
|
||||

|
||||
|
||||
- [Day 27](#day-27)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
|
||||
# Day 27
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Create the following using HTML, CSS, and JavaScript
|
||||
|
||||

|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 26](../26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) | [Day 28 >>](../28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md)
|
@ -0,0 +1,37 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 27](../27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) | [Day 29>>](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md)
|
||||
|
||||

|
||||
|
||||
- [Day 28](#day-28)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
|
||||
# Day 28
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Create the following using HTML, CSS, and JavaScript
|
||||
|
||||

|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 27](../27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) | [Day 29>>](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md)
|
@ -0,0 +1,44 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Animating Characters</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
|
||||
</div>
|
||||
|
||||
[<< Day 28](../28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | [Day 30>>](../30_Day_Mini_project_final/30_day_mini_project_final.md)
|
||||
|
||||

|
||||
|
||||
- [Day 29](#day-29)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
- [Exercise: Livello 2](#exercise-level-2)
|
||||
- [Exercise: Livello 3](#exercise-level-3)
|
||||
|
||||
# Day 29
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Create the following animation using (HTML, CSS, JS)
|
||||
|
||||

|
||||
|
||||
|
||||
### Exercise: Livello 2
|
||||
|
||||
### Exercise: Livello 3
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[<< Day 28](../28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | [Day 30>>](../30_Day_Mini_project_final/30_day_mini_project_final.md)
|
@ -0,0 +1,72 @@
|
||||
<div align="center">
|
||||
<h1> 30 Days Of JavaScript: Final Projects</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>Autore:
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
<small> Gennaio, 2020</small>
|
||||
</sub>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<small>Support the <strong>author</strong> to create more educational materials</small> <br />
|
||||
<a href = "https://www.paypal.me/asabeneh"><img src='./../images/paypal_lg.png' alt='Paypal Logo' style="width:10%"/></a>
|
||||
</div>
|
||||
|
||||
[<< Day 29](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md)
|
||||
|
||||

|
||||
|
||||
- [Day 30](#day-30)
|
||||
- [Esercizi](#exercises)
|
||||
- [Exercise: Livello 1](#exercise-level-1)
|
||||
- [Exercise: Livello 2](#exercise-level-2)
|
||||
- [Exercise: Livello 3](#exercise-level-3)
|
||||
- [Testimony](#testimony)
|
||||
- [Support](#support)
|
||||
|
||||
# Day 30
|
||||
|
||||
## Esercizi
|
||||
|
||||
### Exercise: Livello 1
|
||||
|
||||
1. Create the following animation using (HTML, CSS, JS)
|
||||
|
||||

|
||||
|
||||
2. Validate the following form using regex.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
### Exercise: Livello 2
|
||||
|
||||
### Exercise: Livello 3
|
||||
|
||||
🌕 Your journey to greatness completed successfully. You reached high Livello of greatness. Now, you are much greater than ever before. I knew what it takes to reach to this Livello and you made to this point. You are a real hero. Now, it is time to celebrate your success with a friend or with a family. I am looking forward to seeing you in an other challenge.
|
||||
|
||||
## Testimony
|
||||
|
||||
Now it is time support the author and express your thoughts about the Author and 30DaysOfJavaScript. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/)
|
||||
|
||||
## Support
|
||||
|
||||
You can support the author to produce more educational materials
|
||||
|
||||
[](https://www.paypal.me/asabeneh)
|
||||
|
||||

|
||||
|
||||
[<< Day 29](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md)
|
@ -0,0 +1,846 @@
|
||||
|
||||
# 30 Days Of JavaScript
|
||||
|
||||
| # Giorni | Topics |
|
||||
|
||||
| ----- | :-------------------------------------------------------------------------------------------------------------------------------------------------: |
|
||||
|
||||
| 01 | [Introduzione](./readMe.md) |
|
||||
|
||||
| 02 | [Tipi di dato (Data Types)](./02_Day_Data_types/02_day_data_types.md) |
|
||||
|
||||
| 03 | [Booleans,Operatori, Date](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) |
|
||||
|
||||
| 04 | [Istruzioni Condizionali (Conditionals)](./04_Day_Conditionals/04_day_conditionals.md) |
|
||||
|
||||
| 05 | [Arrays](./05_Day_Arrays/05_day_arrays.md) |
|
||||
|
||||
| 06 | [Loops](./06_Day_Loops/06_day_loops.md) |
|
||||
|
||||
| 07 | [Funzioni](./07_Day_Functions/07_day_functions.md) |
|
||||
|
||||
| 08 | [Oggetti (Objects)](./08_Day_Objects/08_day_objects.md) |
|
||||
|
||||
| 09 | [Funzioni di ordine superiore (Higher Order Functions)](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) |
|
||||
|
||||
| 10 | [Sets e Maps](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) |
|
||||
|
||||
| 11 | [Destrutturazione ed Operatore di Espansione (Destructuring and Spreading)](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) |
|
||||
|
||||
| 12 | [Espressioni Regolari (Regular Expressions)](./12_Day_Regular_expressions/12_day_regular_expressions.md) |
|
||||
|
||||
| 13 | [Metodi dell'Oggetto *Console* (Console Object Methods)](./13_Day_Console_object_methods/13_day_console_object_methods.md) |
|
||||
|
||||
| 14 | [Gestione Errori (Error Handling)](./14_Day_Error_handling/14_day_error_handling.md) |
|
||||
|
||||
| 15 | [Classes](./15_Day_Classes/15_day_classes.md) |
|
||||
|
||||
| 16 | [JSON](./16_Day_JSON/16_day_json.md) |
|
||||
|
||||
| 17 | [Web Storages](./17_Day_Web_storages/17_day_web_storages.md) |
|
||||
|
||||
| 18 | [Promises](./18_Day_Promises/18_day_promises.md) |
|
||||
|
||||
| 19 | [Closure](./19_Day_Closures/19_day_closures.md) |
|
||||
|
||||
| 20 | [Scrivere codice pulito (Writing Clean Code)](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) |
|
||||
|
||||
| 21 | [DOM](./21_Day_DOM/21_day_dom.md) |
|
||||
|
||||
| 22 | [Manipolare l'Oggetto DOM (Manipulating DOM Object)](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) |
|
||||
|
||||
| 23 | [Event Listeners](./23_Day_Event_listeners/23_day_event_listeners.md) |
|
||||
|
||||
| 24 | [Mini Progetto: Sistema Solare (Mini Project: Solar System)](./24_Day_Project_solar_system/24_day_project_solar_system.md) |
|
||||
|
||||
| 25 | [Mini Progetto: Visualizzazione Dati Paesi Nel Mondo (Mini Project: World Countries Data Visualization 1)](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) |
|
||||
|
||||
| 26 | [Mini Progetto: Visualizzazione Dati Paesi Nel Mondo (Mini Project: World Countries Data Visualization 2)](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) |
|
||||
|
||||
| 27 | [Mini Progetto: Portfolio (Mini Project: Portfolio)](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) |
|
||||
|
||||
| 28 | [Mini Progetto: Leaderboard (Mini Project: Leaderboard)](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) |
|
||||
|
||||
| 29 | [Mini Progetto: Animare le Lettere (Mini Project: Animating characters)](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) |
|
||||
|
||||
| 30 | [Progetti Finali (Final Projects)](./30_Day_Mini_project_final/30_day_mini_project_final.md) |
|
||||
|
||||
🧡🧡🧡 BUON CODING 🧡🧡🧡
|
||||
|
||||
<div>
|
||||
|
||||
<small>Supporta l' <strong>autore</strong> nel creare altri materiali educativi</small> <br />
|
||||
|
||||
<a href = "https://www.paypal.me/asabeneh"><img src='../images/paypal_lg.png' alt='Paypal Logo' style="width:10%"/></a>
|
||||
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
|
||||
<h1> 30 Days Of JavaScript: Introduzione</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>Autore:
|
||||
|
||||
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
|
||||
|
||||
<small> Gennaio, 2020</small>
|
||||
|
||||
</sub>
|
||||
|
||||
<div>
|
||||
|
||||
🇬🇧 [English](./readMe.md)
|
||||
|
||||
🇮🇹 [Italian](./Italian/readMe.md)
|
||||
|
||||
🇪🇸 [Spanish](./Spanish/readme.md)
|
||||
|
||||
🇷🇺 [Russian](./RU/README.md)
|
||||
|
||||
🇹🇷 [Turkish](./Turkish/readMe.md)
|
||||
|
||||
🇦🇿 [Azerbaijan](./Azerbaijani/readMe.md)
|
||||
|
||||
🇰🇷 [Korean](./Korea/README.md)
|
||||
|
||||
🇻🇳 [Vietnamese](./Vietnamese/README.md)
|
||||
|
||||
🇵🇱 [Polish](./Polish/readMe.md)
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
[Giorno 2 >>](./02_Day_Data_types/02_day_data_types.md)
|
||||
|
||||

|
||||
|
||||
- [30 Days Of JavaScript](#30-days-of-javascript)
|
||||
|
||||
- [📔 Giorno 1](#-day-1)
|
||||
|
||||
- [Introduzione](#introduction)
|
||||
|
||||
- [Requisiti](#requirements)
|
||||
|
||||
- [Setup](#setup)
|
||||
|
||||
- [Installazione Node.js](#install-nodejs)
|
||||
|
||||
- [Browser](#browser)
|
||||
|
||||
- [Installazione di Google Chrome](#installing-google-chrome)
|
||||
|
||||
- [Apertura Console di Google Chrome](#opening-google-chrome-console)
|
||||
|
||||
- [Scrivere codice sulla Console del Browser](#writing-code-on-browser-console)
|
||||
|
||||
- [Console.log](#consolelog)
|
||||
|
||||
- [Console.log con Argomenti Multipli](#consolelog-with-multiple-arguments)
|
||||
|
||||
- [commenti](#comments)
|
||||
|
||||
- [Sintassi](#syntax)
|
||||
|
||||
- [Aritmetica](#arithmetics)
|
||||
|
||||
- [Editor Codice](#code-editor)
|
||||
|
||||
- [Installazione Visual Studio Code](#installing-visual-studio-code)
|
||||
|
||||
- [Come usare Visual Studio Code](#how-to-use-visual-studio-code)
|
||||
|
||||
- [Aggiungere JavaScript ad una Pagina Web](#adding-javascript-to-a-web-page)
|
||||
|
||||
- [Inline Script](#inline-script)
|
||||
|
||||
- [Internal Script](#internal-script)
|
||||
|
||||
- [External Script](#external-script)
|
||||
|
||||
- [Multipli External Scripts](#multiple-external-scripts)
|
||||
|
||||
- [Introduzione ai Tipi di Dato](#introduction-to-data-types)
|
||||
|
||||
- [Numbers](#numbers)
|
||||
|
||||
- [Strings](#strings)
|
||||
|
||||
- [Booleans](#booleans)
|
||||
|
||||
- [Undefined](#undefined)
|
||||
|
||||
- [Null](#null)
|
||||
|
||||
- [Verificare il Tipo dei Dati](#checking-data-types)
|
||||
|
||||
- [Ancora Commenti](#comments-again)
|
||||
|
||||
- [Variabili](#variables)
|
||||
|
||||
- [💻 Giorno 1: Esercizi](#-day-1-exercises)
|
||||
|
||||
# 📔 Giorno 1
|
||||
|
||||
## Introduzione
|
||||
|
||||
**Congratulazioni** per aver deciso di partecipare a 30 days of JavaScript programming challenge. In questa challenge imparerai tutto quello di cui hai bisogno per essere un programmatore JavaScript, ed in generale, il concetto di programmazione. Al termine della challenge otterrai un certificato di completamento della 30DaysOfJavaScript programming challenge. In caso avessi bisogno di aiuto o vorrei aiutare altri puoi unirti al [gruppo_telegram](https://t.me/ThirtyDaysOfJavaScript).
|
||||
|
||||
**Un 30DaysOfJavaScript** è una challenge sviluppatori JavaScript esperti o alle prime armi. Benvenuto in JavaScript. JavaScript è un linguaggio per il web. Mi piace insegnarlo ed usarlo, spero che lo faccia presto anche tu.
|
||||
|
||||
In questa challenge step by step di JavaScript, imparerai JavaScript, il linguaggio di programmazione più popolare nella storia dell'umanità.
|
||||
|
||||
JavaScript è usato **_per aggiungere interazione ai websites, per sviluppare mobile apps, applicazioni desktop, videogiochi_** ed attualmente JavaScript può essere usato anche in ambito **_machine learning_** e **_AI_**. **_JavaScript (JS)_** è diventato popolare nei ultimi anni ed è il linguaggio più utilizzato su GitHub da sei anni.
|
||||
|
||||
|
||||
|
||||
## Requisiti
|
||||
|
||||
Nessuna conoscenza pregressa è richiesta per seguire questa challenge. Hai solo bisogno di:
|
||||
|
||||
1. Motivazione
|
||||
|
||||
2. Un computer
|
||||
|
||||
3. Internet
|
||||
|
||||
4. Un browser
|
||||
|
||||
5. Un editor code
|
||||
|
||||
## Setup
|
||||
|
||||
Ritengo tu abbia la motivazione ed il forte desiderio per diventare uno sviluppatore. Se è così, allora hai tutto quello che ti server per iniziare.
|
||||
|
||||
### Installazione Node.js
|
||||
|
||||
Potresti non aver bisogno di Node.js adesso ma ne avrai probabilmente bisogno dopo. Installa [node.js](https://nodejs.org/en/).
|
||||
|
||||

|
||||
|
||||
Dopo aver scaricato il file aprilo ed installa node
|
||||
|
||||

|
||||
|
||||
Possiamo controllare l'installazione di node sulla macchina locale aprendo il terminale.
|
||||
|
||||
```sh
|
||||
asabeneh $ node -v
|
||||
|
||||
v12.14.0
|
||||
```
|
||||
|
||||
Nella realizzazione di questo tutorial sto usando Node 12.14.0, potresti avere una versione differente disponibile da installare.
|
||||
|
||||
### Browser
|
||||
|
||||
Ci sono diversi browser disponibili. Io raccomando l'uso di Google Chrome.
|
||||
|
||||
#### Installazione di Google Chrome
|
||||
|
||||
Installa [Google Chrome](https://www.google.com/chrome/). Possiamo scrivere del codice semplice sulla console del browser ma non la utilzzeremo per scrivere codice.
|
||||
|
||||

|
||||
|
||||
#### Apertura della Console di Google Chrome
|
||||
|
||||
Puoi aprire la console di Google Chrome console sia cliccando sui tre puntini nell'angolo in alto a destra del browser, selezionando _Più strumenti -> Strumenti per sviluppatori_ o usando una scorciatoia da tastiera. Preferisco usare le scorciatoie.
|
||||
|
||||

|
||||
|
||||
Per aprire la console di Chrome utilizzando una scorciatoia da tastiera
|
||||
|
||||
```sh
|
||||
Mac
|
||||
|
||||
Command+Option+J
|
||||
|
||||
|
||||
Windows/Linux:
|
||||
|
||||
Ctl+Shift+J
|
||||
```
|
||||
|
||||

|
||||
|
||||
Dopo aver aperto la console di Google Chrome, provate a esplorare i pulsanti contrassegnati. Dedicheremo la maggior parte del tempo alla Console. La Console è il luogo in cui si trova il codice JavaScript. L'engine Google Console V8 trasforma il codice JavaScript in codice macchina.
|
||||
|
||||
Scriviamo un codice JavaScript nella console di Google Chrome:
|
||||
|
||||

|
||||
|
||||
#### Scrivendo codice sulla Console del Browser
|
||||
|
||||
Possiamo scrivere qualsiasi codice JavaScript sulla console di Google o su quella di qualsiasi browser. Tuttavia, per questa sfida, ci concentreremo solo sulla console di Google Chrome. Apri la console utilizzando:
|
||||
|
||||
```sh
|
||||
Mac
|
||||
|
||||
Command+Option+I
|
||||
|
||||
|
||||
Windows:
|
||||
|
||||
Ctl+Shift+I
|
||||
```
|
||||
|
||||
##### Console.log
|
||||
|
||||
|
||||
Per scrivere il nostro primo codice JavaScript, abbiamo utilizzato la funzione integrata **console.log()**. Abbiamo passato un argomento come dato di input e la funzione visualizza l'output. Abbiamo passato `'Hello, World'` come dato di input o argomento nella funzione console.log().
|
||||
```js
|
||||
console.log('Hello, World!')
|
||||
```
|
||||
|
||||
##### Console.log con Argomenti Multipli
|
||||
|
||||
La funzione **`console.log()`** può prendere più parametri separandoli con la virgola. La sintassi è come segue:**`console.log(param1, param2, param3)`**
|
||||
|
||||

|
||||
|
||||
```js
|
||||
console.log('Hello', 'World', '!')
|
||||
console.log('HAPPY', 'NEW', 'YEAR', 2020)
|
||||
console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript')
|
||||
```
|
||||
|
||||
Come si può vedere dal codice snippet qui sopra, _`console.log()`_ accetta argomenti multipli.
|
||||
|
||||
Congratulazioni! Avete scritto il vostro primo codice JavaScript usando _`console.log()`_.
|
||||
|
||||
|
||||
##### Commenti
|
||||
|
||||
|
||||
Possiamo aggiungere commenti al nostro codice. I commenti sono molto importanti per rendere il codice più leggibile e per annorare osservazioni nel nostro codice. JavaScript non esegue la parte di commento del nostro codice. In JavaScript, qualsiasi riga di testo che inizia con // in JavaScript è un commento, e qualsiasi cosa racchiusa come questa `//` è anch'essa un commento.
|
||||
|
||||
**Esempio: Commento su Linea Singola**
|
||||
```js
|
||||
// This is the first comment
|
||||
// This is the second comment
|
||||
// I am a single line comment
|
||||
```
|
||||
|
||||
**Esempio: Commento Multilinea**
|
||||
```js
|
||||
/*
|
||||
This is a multiline comment
|
||||
Multiline comments can take multiple lines
|
||||
JavaScript is the language of the web
|
||||
*/
|
||||
```
|
||||
|
||||
##### Sintassi
|
||||
|
||||
I linguaggi di programmazione sono simili alle lingue umane. L'inglese o molte altre lingue utilizzano parole, frasi, frasi composte e altro ancora per trasmettere un messaggio significativo. Il significato inglese di sintassi è _la disposizione di parole e frasi per creare frasi ben formate in una lingua_. La definizione tecnica di sintassi è la struttura degli enunciati in un linguaggio informatico. I linguaggi di programmazione hanno una sintassi. JavaScript è un linguaggio di programmazione e, come altri linguaggi di programmazione, ha una propria sintassi. Se non scriviamo una sintassi comprensibile in JavaScript, questo darà luogo a diversi tipi di errori. Esploreremo i diversi tipi di errori di JavaScript più avanti. Per ora, vediamo gli errori di sintassi.
|
||||
|
||||
|
||||

|
||||
|
||||
Ho commesso un errore intenzionale. Di conseguenza, la console visualizza gli errori di sintassi. In realtà, la sintassi è molto informativa sul tipo di errore commesso. Leggendo la linea guida di feedback dell'errore, possiamo correggere la sintassi e risolvere il problema. Il processo di identificazione e rimozione degli errori da un programma si chiama debug. Risolviamo gli errori:
|
||||
|
||||
```js
|
||||
console.log('Hello, World!')
|
||||
console.log('Hello, World!')
|
||||
```
|
||||
|
||||
Finora abbiamo visto come visualizzare il testo utilizzando _`console.log()`_. Se si stampa un testo o una stringa utilizzando _`console.log()`_, il testo deve trovarsi all'interno di apici singoli, doppi apici o un backtick.
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
console.log('Hello, World!')
|
||||
console.log("Hello, World!")
|
||||
console.log(`Hello, World!`)
|
||||
```
|
||||
|
||||
#### Aritmetica
|
||||
|
||||
|
||||
Ora facciamo pratica scrivendo codici JavaScript usando _`console.log()`_ sulla console di Google Chrome per i tipi di dati numerici. Oltre al testo, possiamo anche eseguire calcoli matematici utilizzando JavaScript. È possibile scrivere codice JavaScript sulla console di Google Chrome direttamente senza la funzione **`console.log()`_**. Tuttavia, è stata inclusa in questa introduzione perché la maggior parte di questa sfida si svolgerà in un editor di testo, dove l'uso della funzione sarà obbligatorio. È possibile giocare direttamente con le istruzioni della console.
|
||||
|
||||

|
||||
|
||||
```js
|
||||
console.log(2 + 3) // Addition
|
||||
console.log(3 - 2) // Subtraction
|
||||
console.log(2 * 3) // Multiplication
|
||||
console.log(3 / 2) // Division
|
||||
console.log(3 % 2) // Modulus - finding remainder
|
||||
console.log(3 ** 2) // Exponentiation 3 ** 2 == 3 * 3
|
||||
```
|
||||
|
||||
### Editor Codice
|
||||
|
||||
Possiamo scrivere i nostri codici sulla console del browser, ma solo per codice breve. In un ambiente di lavoro reale, gli sviluppatori utilizzano diversi editor di codice per scrivere i loro codici. In questa sfida di 30 giorni di JavaScript, utilizzeremo Visual Studio Code.
|
||||
|
||||
#### Installazione Visual Studio Code
|
||||
|
||||
Visual Studio Code è un editor di testo open-source molto popolare. Raccomanderei di [scaricare Visual Studio Code](https://code.visualstudio.com/), ma se siete favorevoli ad altri editor, sentitevi liberi di seguire con quello che avete.
|
||||
|
||||

|
||||
|
||||
Se avete installato Visual Studio Code, iniziate a usarlo.
|
||||
|
||||
#### Come Usare Visual Studio Code
|
||||
|
||||
Aprire Visual Studio Code facendo doppio clic sulla sua icona. Quando si apre, si ottiene questo tipo di interfaccia. Provate a interagire con le icone etichettate.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
## Aggiungere JavaScript ad una Pagina Web
|
||||
|
||||
JavaScript può essere aggiunto a una pagina web in tre modi diversi:
|
||||
|
||||
- **_Inline script_**
|
||||
|
||||
- **_Internal script_**
|
||||
|
||||
- **_External script_**
|
||||
|
||||
- **_Multiple External scripts_**
|
||||
|
||||
Le sezioni seguenti mostrano diversi modi per aggiungere codice JavaScript alla pagina Web.
|
||||
### Inline Script
|
||||
|
||||
Crea una cartella di progetto sul desktop o in una posizione qualsiasi, denominala 30DaysOfJS e crea un file **_`index.html`_** nella cartella di progetto. Incolla quindi il seguente codice e aprilo in un browser, ad esempio [Chrome].(https://www.google.com/chrome/).
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DaysOfScript:Inline Script</title>
|
||||
</head>
|
||||
<body>
|
||||
<button onclick="alert('Welcome to 30DaysOfJavaScript!')">Click Me</button>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Ora, hai appena scritto il tuo primo script inline. Possiamo creare un messaggio di avviso a comparsa usando la funzione incorporata _`alert()`_.
|
||||
|
||||
### Internal Script
|
||||
|
||||
Gli internal script possono essere inseriti nel _`head`_ o nel _`body`_, ma è preferibile inserirli nel body del documento HTML.
|
||||
|
||||
Per prima cosa, scriviamo nella parte iniziale della pagina.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DaysOfScript:Internal Script</title>
|
||||
<script>
|
||||
console.log('Welcome to 30DaysOfJavaScript')
|
||||
</script>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Nella maggior parte dei casi è così che si scrive uno script interno. Scrivere il codice JavaScript nella sezione del corpo è l'opzione preferita. Aprire la console del browser per vedere l'output di `console.log()`.
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DaysOfScript:Internal Script</title>
|
||||
</head>
|
||||
<body>
|
||||
<button onclick="alert('Welcome to 30DaysOfJavaScript!');">Click Me</button>
|
||||
<script>
|
||||
console.log('Welcome to 30DaysOfJavaScript')
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Aprire la console del browser per vedere l'output di `console.log()`.
|
||||
|
||||

|
||||
|
||||
### External Script
|
||||
|
||||
Come per Internal Script , il link all'External Script può essere presente nell'intestazione o nel corpo, ma è preferibile inserirlo nel corpo.
|
||||
Per prima cosa, occorre creare un file JavaScript esterno con estensione .js. Tutti i file che terminano con l'estensione .js sono file JavaScript. Creare un file chiamato introduction.js all'interno della cartella del progetto e scrivere il seguente codice e collegare questo file .js in fondo al body.
|
||||
```js
|
||||
console.log('Welcome to 30DaysOfJavaScript')
|
||||
```
|
||||
|
||||
External scripts nel _head_:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DaysOfJavaScript:External script</title>
|
||||
<script src="introduction.js"></script>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
```
|
||||
|
||||
External scripts nel _body_:
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>30DaysOfJavaScript:External script</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- JavaScript external link could be in the header or in the body -->
|
||||
|
||||
<!-- Before the closing tag of the body is the recommended place to put the external JavaScript script -->
|
||||
|
||||
<script src="introduction.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
```
|
||||
|
||||
Aprite la console del browser per vedere l'output del metodo `console.log()`.
|
||||
|
||||
|
||||
### Multipli External Scripts
|
||||
|
||||
Possiamo anche collegare più file JavaScript esterni a una pagina web.
|
||||
Creare un file `helloworld.js` all'interno della cartella 30DaysOfJS e scrivere il seguente codice.
|
||||
|
||||
```js
|
||||
console.log('Hello, World!')
|
||||
```
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Multiple External Scripts</title>
|
||||
</head>
|
||||
<body>
|
||||
<script src="./helloworld.js"></script>
|
||||
<script src="./introduction.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
_Il file main.js deve trovarsi sotto tutti gli altri script_. È molto importante ricordarlo.
|
||||
|
||||

|
||||
|
||||
|
||||
## Introduzione ai Tipi di Dato
|
||||
|
||||
|
||||
In JavaScript e in altri linguaggi di programmazione esistono diversi tipi di dati. I seguenti sono tipi di dati primitivi di JavaScript: _String, Number, Boolean, undefined, Null_, e _Symbol_.
|
||||
|
||||
|
||||
### Numbers
|
||||
- Integers: Numeri interi (negativi, zero e positivi)
|
||||
|
||||
Esempio:
|
||||
|
||||
... -3, -2, -1, 0, 1, 2, 3 ...
|
||||
|
||||
- Float-point: Numeri decimali
|
||||
|
||||
Esempio
|
||||
|
||||
... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ...
|
||||
|
||||
### Strings
|
||||
|
||||
Un insieme di uno o più caratteri compresi tra due apici singoli, doppi apici o backtick.
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
'a'
|
||||
'Asabeneh'
|
||||
"Asabeneh"
|
||||
'Finland'
|
||||
'JavaScript is a beautiful programming language'
|
||||
'I love teaching'
|
||||
'I hope you are enjoying the first day'
|
||||
`We can also create a string using a backtick`
|
||||
'A string could be just as small as one character or as big as many pages'
|
||||
'Any data type under a single quote, double quote or backtick is a string'
|
||||
```
|
||||
|
||||
### Booleans
|
||||
|
||||
Un valore booleano è vero o falso. Qualsiasi confronto restituisce un valore booleano che può essere vero o falso.
|
||||
|
||||
Un tipo di dati booleano è un valore vero o falso.
|
||||
|
||||
**Esempio:**
|
||||
|
||||
```js
|
||||
true // if the light is on, the value is true
|
||||
|
||||
false // if the light is off, the value is false
|
||||
```
|
||||
|
||||
### Undefined
|
||||
|
||||
|
||||
In JavaScript, se non si assegna un valore a una variabile, il valore è undefined. Inoltre, se una funzione non restituisce nulla, restituisce undefined.
|
||||
|
||||
```js
|
||||
let firstName
|
||||
console.log(firstName) // undefined, because it is not assigned to a value yet
|
||||
```
|
||||
|
||||
### Null
|
||||
|
||||
Null in JavaScript significa valore vuoto.
|
||||
|
||||
```js
|
||||
let emptyValue = null
|
||||
```
|
||||
|
||||
## Verificando i Tipi di dato
|
||||
|
||||
Per verificare il tipo di dati di una determinata variabile, si utilizza l'operatore **typeof**. Si veda l'esempio seguente.
|
||||
|
||||
```js
|
||||
console.log(typeof 'Asabeneh') // string
|
||||
|
||||
console.log(typeof 5) // number
|
||||
|
||||
console.log(typeof true) // boolean
|
||||
|
||||
console.log(typeof null) // object type
|
||||
|
||||
console.log(typeof undefined) // undefined
|
||||
|
||||
```
|
||||
|
||||
## Ancora Commenti
|
||||
|
||||
|
||||
Ricordate che i commenti in JavaScript sono simili a quelli di altri linguaggi di programmazione. I commenti sono importanti per rendere il codice più leggibile.
|
||||
|
||||
Esistono due modi per commentare:
|
||||
|
||||
- _Single line commenting_
|
||||
|
||||
- _Multiline commenting_
|
||||
|
||||
```js
|
||||
// commenting the code itself with a single comment
|
||||
|
||||
// let firstName = 'Asabeneh'; single line comment
|
||||
|
||||
// let lastName = 'Yetayeh'; single line comment
|
||||
```
|
||||
|
||||
Commento Multilinea:
|
||||
|
||||
```js
|
||||
/*
|
||||
|
||||
let location = 'Helsinki';
|
||||
|
||||
let age = 100;
|
||||
|
||||
let isMarried = true;
|
||||
|
||||
This is a Multiple line comment
|
||||
|
||||
*/
|
||||
```
|
||||
|
||||
## Variables
|
||||
|
||||
|
||||
Le variabili sono _contenitori_ di dati. Le variabili vengono utilizzate per _immagazzinare_ i dati in una posizione di memoria. Quando una variabile viene dichiarata, viene riservata una posizione di memoria. Quando ad una variabile viene assegnato un valore (dati), lo spazio di memoria verrà riempito con quei dati. Per dichiarare una variabile, si usano le parole chiave _var_, _let_ o _const_.
|
||||
|
||||
Per una variabile che cambia in un momento diverso, si usa _let_. Se i dati non cambiano affatto, si usa _const_. Ad esempio, PI, nome del paese, gravità non cambiano e possiamo usare _const_. In questa sfida non useremo var e non ti consiglio di usarlo. È un modo di dichiarare le variabili soggetto a errori e ha molte perdite. Parleremo più dettagliatamente di var, let e const in altre sezioni (ambito). Per ora, la spiegazione di cui sopra è sufficiente.
|
||||
|
||||
Un nome di variabile JavaScript valido deve seguire le seguenti regole:
|
||||
|
||||
- Il nome di una variabile JavaScript non deve iniziare con un numero.
|
||||
|
||||
- Il nome di una variabile JavaScript non ammette caratteri speciali, tranne il segno del dollaro e il trattino basso.
|
||||
|
||||
- Il nome di una variabile JavaScript segue la convenzione camelCase.
|
||||
|
||||
- Il nome di una variabile JavaScript non deve avere spazi tra le parole.
|
||||
|
||||
I seguenti sono esempi di variabili JavaScript valide.
|
||||
|
||||
```js
|
||||
firstName
|
||||
|
||||
lastName
|
||||
|
||||
country
|
||||
|
||||
city
|
||||
|
||||
capitalCity
|
||||
|
||||
age
|
||||
|
||||
isMarried
|
||||
|
||||
first_name
|
||||
|
||||
last_name
|
||||
|
||||
is_married
|
||||
|
||||
capital_city
|
||||
|
||||
num1
|
||||
|
||||
num_1
|
||||
|
||||
_num_1
|
||||
|
||||
$num1
|
||||
|
||||
year2020
|
||||
|
||||
year_2020
|
||||
|
||||
```
|
||||
|
||||
La prima e la seconda variabile dell'elenco seguono la convenzione camelCase della dichiarazione in JavaScript. In questa challenge, utilizzeremo le variabili camelCase (camelWithOneHump). Utilizzeremo CamelCase (CamelWithTwoHump) per dichiarare le classi; parleremo di classi e oggetti in un'altra sezione.
|
||||
|
||||
Esempio di variabili non valide:
|
||||
|
||||
```js
|
||||
first-name
|
||||
|
||||
1_num
|
||||
|
||||
num_#_1
|
||||
|
||||
```
|
||||
|
||||
Dichiariamo variabili con tipi di dati diversi. Per dichiarare una variabile, dobbiamo usare la parola chiave _let_ o _const_ prima del nome della variabile. Dopo il nome della variabile, scriviamo un segno di uguale (operatore di assegnazione) e un valore (dati assegnati).
|
||||
|
||||
```js
|
||||
// Syntax
|
||||
let nameOfVariable = value
|
||||
```
|
||||
|
||||
Il nameOfVariable è il nome che memorizza i diversi dati del valore. Vedi degli esempi dettagliati.
|
||||
|
||||
**Esempi di variabili dichiarate**
|
||||
|
||||
```js
|
||||
// Declaring different variables of different data types
|
||||
|
||||
let firstName = 'Asabeneh' // first name of a person
|
||||
|
||||
let lastName = 'Yetayeh' // last name of a person
|
||||
|
||||
let country = 'Finland' // country
|
||||
|
||||
let city = 'Helsinki' // capital city
|
||||
|
||||
let age = 100 // age in years
|
||||
|
||||
let isMarried = true
|
||||
|
||||
console.log(firstName, lastName, country, city, age, isMarried)
|
||||
|
||||
```
|
||||
|
||||
```sh
|
||||
Asabeneh Yetayeh Finland Helsinki 100 true
|
||||
|
||||
```
|
||||
|
||||
```js
|
||||
// Declaring variables with number values
|
||||
|
||||
let age = 100 // age in years
|
||||
|
||||
const gravity = 9.81 // earth gravity in m/s2
|
||||
|
||||
const boilingPoint = 100 // water boiling point, temperature in °C
|
||||
|
||||
const PI = 3.14 // geometrical constant
|
||||
|
||||
console.log(gravity, boilingPoint, PI)
|
||||
|
||||
```
|
||||
|
||||
```sh
|
||||
9.81 100 3.14
|
||||
|
||||
```
|
||||
|
||||
```js
|
||||
// Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble
|
||||
|
||||
let name = 'Asabeneh', job = 'teacher', live = 'Finland'
|
||||
|
||||
console.log(name, job, live)
|
||||
|
||||
```
|
||||
|
||||
```sh
|
||||
Asabeneh teacher Finland
|
||||
```
|
||||
I file del codice sono disposti nelle cartelle x-Day nella directory principale della repository.
|
||||
Quando si esegue il file _index.html_ nella cartella 01-Day si dovrebbe ottenere questo risultato:
|
||||
|
||||

|
||||
|
||||
🌕 fantastico! hai appena completato la sfida del primo giorno e sei sulla strada della grandezza. Ora fai qualche esercizio per il cervello e i muscoli.
|
||||
|
||||
# 💻 Giorno 1: Esercizi
|
||||
|
||||
|
||||
1. Scrivete un commento di una sola riga che dice: "I commenti possono rendere il codice leggibile".
|
||||
2. Scrivete un altro commento di una sola riga che dica: _Benvenuti a 30DaysOfJavaScript_.
|
||||
3. Scrivete un commento di più righe che dica: "I commenti possono rendere il codice leggibile, facile da riutilizzare ed informativo".
|
||||
4. Creare un file variable.js, dichiarare le variabili e assegnare i tipi di dati string, boolean, undefined e null.
|
||||
5. Creare il file datatypes.js e utilizzare l'operatore JavaScript **_typeof_** per verificare i diversi tipi di dati. Controllare il tipo di dati di ogni variabile
|
||||
6. Dichiarare quattro variabili senza assegnare valori
|
||||
7. Dichiarare quattro variabili con valori assegnati
|
||||
8. Dichiarare le variabili per memorizzare il proprio nome, cognome, stato civile, paese ed età in più righe.
|
||||
9. Dichiarare le variabili per memorizzare il nome, il cognome, lo stato civile, il Paese e l'età in un'unica riga.
|
||||
10. Dichiarare due variabili _myAge_ e _yourAge_, assegnare loro i valori iniziali e registrarli nella console del browser.
|
||||
|
||||
```sh
|
||||
I am 25 years old.
|
||||
You are 30 years old.
|
||||
```
|
||||
|
||||
🎉 CONGRATULAZIONI ! 🎉
|
||||
|
||||
[Giorno 2 >>](./02_Day_Data_types/02_day_data_types.md)
|
Loading…
Reference in new issue