Merge pull request #2 from IDevlin/gh-pruebas

Gh pruebas
pull/387/head
Jose 3 years ago committed by GitHub
commit 19dfe10ca0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -62,12 +62,12 @@ Primitive data types in JavaScript include:
3. Booleans - true or false value
4. Null - empty value or no value
5. Undefined - a declared variable without a value
6. Symbol - A unique value that can be generated by Symbol constructor
Non-primitive data types in JavaScript includes:
1. Objects
2. Functions
3. Arrays
2. Arrays
Now, let us see what exactly primitive and non-primitive data types mean.
*Primitive* data types are immutable(non-modifiable) data types. Once a primitive data type is created we cannot modify it.

@ -59,7 +59,7 @@ An array is a collection of different data types which are ordered and changeabl
### How to create an empty array
In JavaScript, we can create an array in different ways. Let us see different ways to create an array.
It is very common to use *const* instead of *let* to declare an array variable. If you ar using const it means you do not use that variable name again.
It is very common to use _const_ instead of _let_ to declare an array variable. If you ar using const it means you do not use that variable name again.
- Using Array constructor
@ -400,7 +400,7 @@ if(index === -1){
// 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 a avocado 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')
@ -521,18 +521,20 @@ Splice: It takes three parameters:Starting position, number of times to be remov
```js
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.splice()) // -> remove all items
numbers.splice()
console.log(numbers) // -> remove all items
```
```js
const numbers = [1, 2, 3, 4, 5]
console.log(numbers.splice(0,1)) // remove the first item
numbers.splice(0,1)
console.log(numbers) // remove the first item
```
```js
const numbers = [1, 2, 3, 4, 5, 6];
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
```
@ -544,7 +546,6 @@ Push: adding item in the end. To add item to the end of an existing array we use
// syntax
const arr = ['item1', 'item2','item3']
arr.push('new item')
console.log(arr)
// ['item1', 'item2','item3','new item']
```
@ -552,7 +553,6 @@ console.log(arr)
```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
@ -562,7 +562,6 @@ 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')
@ -576,7 +575,6 @@ pop: Removing item in the end.
```js
const numbers = [1, 2, 3, 4, 5]
numbers.pop() // -> remove one item from the end
console.log(numbers) // -> [1,2,3,4]
```
@ -587,7 +585,6 @@ shift: Removing one array element in the beginning of the array.
```js
const numbers = [1, 2, 3, 4, 5]
numbers.shift() // -> remove one item from the beginning
console.log(numbers) // -> [2,3,4,5]
```
@ -598,7 +595,6 @@ unshift: Adding array element in the beginning of the array.
```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]
```
@ -609,7 +605,6 @@ reverse: reverse the order of an array.
```js
const numbers = [1, 2, 3, 4, 5]
numbers.reverse() // -> reverse array order
console.log(numbers) // [5, 4, 3, 2, 1]
numbers.reverse()
@ -769,7 +764,7 @@ const webTechs = [
- Find the median age(one middle item or two middle items divided by two)
- Find the average age(all items divided by number of items)
- Find the range of the ages(max minus min)
- Compare the value of (min - average) and (max - average), use *abs()* method
- Compare the value of (min - average) and (max - average), use _abs()_ method
1.Slice the first ten countries from the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
1. Find the middle country(ies) in the [countries array](https://github.com/Asabeneh/30DaysOfJavaScript/tree/master/data/countries.js)
2. Divide the countries array into two equal arrays if it is even. If countries array is not even , one more country for the first half.

@ -273,7 +273,7 @@ const sumAllNums = (...args) => {
console.log(args)
}
sumAllNums(1, 2, 3, 4))
sumAllNums(1, 2, 3, 4)
// [1, 2, 3, 4]
```

@ -391,7 +391,7 @@ _Object.keys_: To get the keys or properties of an object as an array
```js
const keys = Object.keys(copyPerson)
console.log(keys) //['name', 'age', 'country', 'skills', 'address', 'getPersonInfo']
console.log(keys) //['firstName', 'age', 'country','city', 'skills','title', 'address', 'getPersonInfo']
const address = Object.keys(copyPerson.address)
console.log(address) //['street', 'pobox', 'city']
```

@ -1,2 +1,369 @@
console.log(countries)
alert('Open the console and check if the countries has been loaded')
//alert('Open the console and check if the countries has been loaded')
//1. Create an empty object called dog
const dog = new Object()
//2.Print the the dog object on the console
console.log(dog)
//3.Add name, legs, color, age and bark properties for the dog object. The bark property is a method which return woof woof
dog.name = 'Tobby'
dog.legs = 4
dog.color = 'brown'
dog.age = 1
dog.bark = function(){
return 'woof woof'
}
console.log(dog)
//4.Get name, legs, color, age and bark value from the dog object
const entries = Object.values(dog)
console.log(entries)
//5.Set new properties the dog object: breed, getDogInfo
dog.breed = 'mix'
dog.getDogInfo = function(){
return `${this.name} ${this.color} ${this.breed}`
}
console.log(dog.getDogInfo())
console.log(dog)
// Exercises: Level 2
//1.Find the person who has many skills in the users object.
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
}
}
console.log(users)
const usersIds = Object.keys(users)
const userSkills = [];
for(user in usersIds ){
userSkills[user] = users[usersIds[user]].skills.length
}
console.log(users[usersIds[user]].skills.length)
const maxUsersSkills = () => {
console.log(userSkills)
const max = Math.max(...userSkills)
for(user in usersIds){
if(userSkills[user]== max)
return `User with maximun Skills is ${usersIds[user]} `
}
}; console.log(maxUsersSkills())
//2.Count logged in users, count users having greater or equal to 50 points from the following object.
function countLogsAndPoints () {
const userIds = Object.keys(users);
let countLoggedIn = 0;
let countUserPoints = 0
for (user in userIds) {
if (users[userIds[user]].isLoggedIn == true) {
countLoggedIn++;
}
if(users[userIds[user]].points >= 50 ){
countUserPoints++
}
}
return `Users logged are ${countLoggedIn}, Users points greater or equal to 50 are ${countUserPoints} `
}; console.log(countLogsAndPoints())
//3. Find people who are MERN stack developer from the users object
function whoAreMern () {
mernDev = []
const usersIds =Object.keys(users)
for(user in usersIds){
usersSkills = users[usersIds[user]].skills
if(usersSkills.includes('MongoDB' && 'Express' && 'React' && 'Node')){
mernDev.push(usersIds[user])
}
}; return mernDev.join(', ')
}; console.log(whoAreMern())
//4. Set your name in the users object without modifying the original users object
let newUsers = {...users}
newUsers.Jose = {
email: 'jose@gmail.com',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 30,
isLoggedIn: true,
points: 50
}
console.log(newUsers)
//5. Get all keys or properties of users object
const entriesNewUsers = Object.entries(users)
console.log(entriesNewUsers)
//6. Get all the values of users object
const values = Object.values(users)
console.log(values)
//7. Use the countries object to print a country name, capital, populations and languages.
for (let i = 0; i < countries.length; i++) {
let name = countries[i]['name'];
let capital = countries[i]['capital'];
let population = countries[i]['population'];
let languages = countries[i]['languages'];
console.log(`${name}, ${capital}, ${population}, ${languages}`);
}
// Exercises: Level 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.
const personAccount = {
firstName: 'Jane',
lastName: 'Doe',
incomes: {
salary: 5000,
onlinecourses: 15000,
parttime: 1000
},
expenses: {
groceries: 1500,
bills: 3000
},
getTotalIncomes(){
const incomesFrom = Object.keys(this.incomes);
let addIncomes = 0;
for (let i = 0; i < incomesFrom.length; i++){
addIncomes += this.incomes[incomesFrom[i]]
};
return addIncomes;
},
getTotalExpenses () {
const expensesFrom = Object.values(this.expenses);
return expensesFrom.reduce((acc, curr) => acc + curr);
}
};
console.log(personAccount.getTotalIncomes());
console.log(personAccount.getTotalExpenses());
//2.**** Questions:2, 3 and 4 are based on the following two arrays:users and products ()
const usersArr = [
{
_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
//let userNameInput = prompt('Enter your first name.')
function signUp() {
const usernames = [];
for (let i = 0; i < usersArr.length; i++) {
usernames.push(usersArr[i].username);
}
if (usernames.includes(userNameInput)) {
console.log(`${userNameInput} already exist.`);
} else {
signIn();
}
}
function signIn() {
const newUser = {};
newUser._id = generateId();
newUser.username = userNameInput
newUser.email = prompt('Enter your email address.');
newUser.password = prompt('Set your password.', '6 digits of number');
newUser.createdAt = generateTime();
newUser.isLoggedIn = true;
usersArr.push(newUser);
}
function generateId() {
let possible = 'abcdefghijklmnopqrstuvwxyz0123456789';
const id = [];
for (let i = 0; i < 6; i++) {
id.push(possible.charAt(Math.floor(Math.random() * possible.length)));
}
return id.join('');
}
const generateTime = () => {
const now = new Date()
const day = `${(now.getDate())}`.padStart(2,'0');
const month = `${(now.getMonth()+1)}`.padStart(2,'0');
const year = now.getFullYear();
const date = now.getDate();
const minutes = now.getMinutes()
const hours = now.getHours()
return `${day}/${month}/${year}/${hours}:${minutes}`
}
//console.log(signUp());
console.log(usersArr)
/*let userNameInput = "Enteryour firstname".replace(/\s/g, '_')
console.log(userNameInput)*/
//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
//a.
function rateProduct(name) {
for (let i = 0; i < products.length; i++) {
if (products[i].name == name) {
return products[i].ratings;
}
}
}
console.log(rateProduct('mobile phone'));
function averageRating(name) {
let ratingArr = rateProduct(name);
if (ratingArr.length === 0) {
console.log('Ratings not found');
} else if (ratingArr.length) {
let rateSum = 0;
for (let i = 0; i < ratingArr.length; i++) {
rateSum += ratingArr[i].rate;
}
console.log(rateSum / ratingArr.length);
}
}
averageRating('mobile phone');
averageRating('Laptop')
averageRating('TV')
//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.
/*function currentUser() {
let userNameInput = prompt('Enter your first name.');
for (let i = 0; i < users.length; i++) {
if (users[i].username === userNameInput) {
let userId = users[i]._id;
return userId;
}
}
}*/

@ -88,7 +88,7 @@ console.log(higherOrder(2)(3)(10))
Let us see were we use call back functions. For instance the _forEach_ method uses call back.
```js
const numbers = [1, 2, 3, 4]
const numbers = [1, 2, 3, 4, 5]
const sumArray = arr => {
let sum = 0
const callback = function(element) {
@ -518,7 +518,7 @@ console.log(numbers) //[100, 37, 9.81, 3.14]
#### Sorting Object Arrays
When ever we sort objects in an array. We use the object key to compare. Lets see the example below.
Whenever we sort objects in an array, we use the object key to compare. Let us see the example below.
```js
objArr.sort(function (a, b) {
@ -538,7 +538,7 @@ objArr.sort(function (a, b) {
const users = [
{ name: 'Asabeneh', age: 150 },
{ name: 'Brook', age: 50 },
{ name: 'Eyo', age: 100 },
{ name: 'Eyob', age: 100 },
{ name: 'Elias', age: 22 },
]
users.sort((a, b) => {

@ -1,2 +1,440 @@
console.log(countries)
alert('Open the console and check if the countries has been loaded')
//alert('Open the console and check if the countries has been loaded')
//Exercises.
//Exercises: Level 1
const countries_ = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const products = [
{ product: 'banana', price: 3 },
{ product: 'mango', price: 6 },
{ product: 'potato', price: ' ' },
{ product: 'avocado', price: 8 },
{ product: 'coffee', price: 10 },
{ product: 'tea', price: '' },
]
//1. Explain the difference between forEach, map, filter, and reduce.
//forEach() itera sobre cada elemento del array y le aplica la cuncion callback, no retorna nada a diferencia de map(); el metodo map() recorre la matriz y devuelve una nueva matriz modificada con la condiciones dadas en la funcion cb podria decir que aplica la funcion callback a cada elemento del array. el metodo filter()recorre el array y filtra los objetos que cumplan con la condicion de la funcion callback recibe tres parametros elemento, el indice y el array estos dos ultimos son opcionales. el metodo reduce() recibe dos parametros un acumulador acc y un valor actual curr al final retorna el acumulador, es decir el valor acumulado de cada elemento curr
//2. Define a callback function before you use it in forEach, map, filter or reduce.
function callback (element) {
console.log(element)
}
function uppercase (element) {
return element.toUpperCase()
}
//3. Use forEach to console.log each country in the countries array.
countries_.forEach(callback)
//4. Use forEach to console.log each name in the names array.
names.forEach(callback)
//5. Use forEach to console.log each number in the numbers array.
numbers.forEach(callback)
//6. Use map to create a new array by changing each country to uppercase in the countries array.
const newUpperCaseArray = countries_.map(uppercase)
console.log(newUpperCaseArray)
//7. Use map to create an array of countries length from countries array.
const newCountriesArray = countries_.map(el => el)
console.log(newCountriesArray)
//8. Use map to create a new array by changing each number to square in the numbers array
let numbersToSquare = numbers.map(el => el ** 2)
console.log(numbersToSquare)
//9. Use map to change to each name to uppercase in the names array
console.log(names.map(el => el.toUpperCase()))
//10. Use map to map the products array to its corresponding prices.
const corresponding = products.map(el => {
let newObj = []
newObj.push( el.product, el.price)
return newObj
})
console.log(corresponding)
//11. Use filter to filter out countries containing land.
console.log(countries.filter(el => el.name.includes('land')))
//12 Use filter to filter out countries having six character.
console.log(countries.filter(el => el.name.length === 6))
//13.Use filter to filter out countries containing six letters and more in the country array.
console.log(countries.filter(el => el.name.length >= 6))
//14. Use filter to filter out country start with 'E';
console.log(countries.filter(el => el.name.startsWith('E')))
//15. Use filter to filter out only prices with values.
const pricesValues = products.filter(el => typeof el.price === 'number')
console.log(pricesValues)
//16 Declare a function called getStringLists which takes an array as a parameter and then returns an array only with string items.
let arrMix = [1,'Hola', 23, 'Mundo', 45, 2]
function getStringLists (arr) {
return arr.filter(el => typeof el === 'string')
}
//17. Use reduce to sum all the numbers in the numbers array.
console.log(numbers.reduce((acc, curr) => acc + curr))
//18. Use reduce to concatenate all the countries and to produce this sentence: Estonia, Finland, Sweden, Denmark, Norway, and IceLand are north European countries
const concatenateCountries = countries.reduce((acc, curr) => {
return acc.concat(curr.name)
},[])
console.log(concatenateCountries)
//19. Explain the difference between some and every
// some() recorre el array y comprueba si al menos un elemento cumple con la o las condiciones de la funcion callback retorna un booleano y devuleve false en un array vacio
// el metodo every() a direrencia de some comprueba si todos los elementos del array satisfacen la condicion de la funcion callback
//20. Use some to check if some names' length greater than seven in names array
console.log(names.some(el => el.length > 7))
//21.Use every to check if all the countries contain the word land
console.log(countries_.every(el => el.includes('land')))
//22. Explain the difference between find and findIndex.
// find() retorna el primer valor del elemento que satisface la condicion dada en la funcion callback, mientras que findIndex() retorna el primer indice del elemento que satisface la condicion de la funcion. find retorna el valor y findIdex el indice
//23. Use find to find the first country containing only six letters in the countries array
console.log(countries_.find(el => el.length === 6 ))
//24. Use findIndex to find the position of the first country containing only six letters in the countries array
console.log(countries_.findIndex(el => el.length === 6 ))
//25. Use findIndex to find the position of Norway if it doesn't exist in the array you will get -1.
console.log(countries_.findIndex(el => el ==='Norway' ))
//26. Use findIndex to find the position of Russia if it doesn't exist in the array you will get -1.
console.log(countries_.findIndex(el => el ==='Russia' ))
//Exercises: Level 2
//Find the total price of products by chaining two or more array
//iterators(eg. arr.map(callback).filter(callback).reduce(callback))
let sumPricePoducts = products.filter(el => typeof el.price === 'number').reduce((acc, curr) => acc + curr.price,0)//27
console.log(`the total sum of prices from products is ${sumPricePoducts}`)
//2. Find the sum of price of products using only reduce reduce(callback))
console.log(products.filter(el => typeof el.price === 'number').reduce((acc, curr) => acc + curr.price,0))
//3.Declare a function called categorizeCountries which returns an array of countries which have some common pattern(you find the countries array in this repository as countries.js(eg 'land', 'ia', 'island','stan')).
function categorizeCountries(arr) {
const pattern = ['land', 'ia', 'Island', 'stan'];
const categorized = [];
pattern.forEach((element) => {
const sort = [];
//use string template
let category = `${element}`;
categorized.push(arr.filter((country) =>
country.includes(`${element}`)))
});
return categorized;
}
console.log(categorizeCountries(concatenateCountries));
//4. Create a function which return an array of objects, which is the letter and the number of times the letter use to start with a name of a country.
function initialAndTimes(arr) {
const array = [];
const abc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
abc.forEach((letter) => {
const object = {};
object.letter = `${letter}`;
object.times = arr.filter((country) =>
country.startsWith(`${letter}`)).length;
array.push(object);
})
return array;
}
console.log(initialAndTimes(concatenateCountries));
//5. Declare a getFirstTenCountries function and return an array of ten countries. Use different functional programming to work on the countries.js array
function getFirstTenCountries() {
const firstTenCountries = countries.filter((element) => {
return countries.indexOf(element) < 10;
})
return firstTenCountries;
}
console.log(getFirstTenCountries());
//6. Declare a getLastTenCountries function which which returns the last ten countries in the countries array.
function getLastTenCountries() {
const lastTenCountries = countries.filter((element) =>
countries.indexOf(element) > countries.length - 11
)
return lastTenCountries;
}
console.log(getLastTenCountries());
//7. Find out which letter is used many times as initial for a country name from the countries array (eg. Finland, Fiji, France etc)
function mostUsedInitial(arr) {
const abc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const initial = [];
abc.forEach((letter) => {
let initialNum = arr.filter((country) =>
country.startsWith(`${letter}`)).length;
initial.push(initialNum);
})
let max = Math.max(...initial);
let index = initial.indexOf(max);
return abc[index];
}
console.log(mostUsedInitial(concatenateCountries));
// Exercises: Level 3
//1. Use the countries information, in the data folder. Sort countries by name, by capital, by population
const sortedCountries = [];
const criteria = ['name', 'capital', 'population']
criteria.forEach(el => {
const obj ={}
obj[el] = countries.map( country => country[el])
sortedCountries.push(obj)
})
console.log(sortedCountries)
//2. Find the 10 most spoken languages:
//Your output should look like this
/*console.log(mostSpokenLanguages(countries, 10))
[
{country: 'English',count:91},
{country: 'French',count:45},
{country: 'Arabic',count:25},
{country: 'Spanish',count:24},
{country:'Russian',count:9},
{country:'Portuguese', count:9},
{country:'Dutch',count:8},
{country:'German',count:7},
{country:'Chinese',count:5},
{country:'Swahili',count:4}
]
console.log(mostSpokenLanguages(countries, 3))
[
{country: 'English',count: 91},
{country: 'French',count: 45},
{country: 'Arabic',count: 25},
]*/
function mostSpokenLanguages(number) {
//make a language index
const allLangs = countries.map((element) =>
element.languages
);
const mixedLangs = allLangs.toString().split(',');
const langIndex = [...new Set(mixedLangs)]
//get the count of each language
function getLangSum(language) {
let sum = 0;
allLangs.forEach((element) => {
const langNum = element.filter((lang) =>
lang == language).length;
sum += langNum;
})
return sum;
}
//make objects containing language and count
const spokenLangs = [];
langIndex.forEach((element) => {
const object = {};
object.language = `${element}`;
object.count = getLangSum(`${element}`);
spokenLangs.push(object);
})
//sort the objects by the counts in descending order
const mostSpokenLangs = spokenLangs.sort((a, b) =>
b.count - a.count
);
//print out the specified number of objects
const printOut = mostSpokenLangs.filter((element) =>
mostSpokenLangs.indexOf(element) < number)
return printOut;
}
console.log(mostSpokenLanguages(5));
//3. Use countries_data.js file create a function which create the ten most populated countries
/*console.log(mostPopulatedCountries(countries, 10))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000},
{country: 'Indonesia', population: 258705000},
{country: 'Brazil', population: 206135893},
{country: 'Pakistan', population: 194125062},
{country: 'Nigeria', population: 186988000},
{country: 'Bangladesh', population: 161006790},
{country: 'Russian Federation', population: 146599183},
{country: 'Japan', population: 126960000}
]*/
function mostPopulatedCountries(number) {
//make a new array containing objects with country and population
const countriesAndPopulation = [];
countries.forEach((element) => {
const object = {};
object.country = element.name;
object.population = element.population;
countriesAndPopulation.push(object);
})
//sort the objects by its population
const mostPopulated = countriesAndPopulation.sort((a, b) =>
b.population - a.population
);
//print out the specified number of objects
const printOut = mostPopulated.filter((element) =>
mostPopulated.indexOf(element) < number)
return printOut;
}
console.log(mostPopulatedCountries(3));
//4. Try to develop a program which calculate measure of central tendency of a sample(mean, median, mode) and measure of variability(range, variance, standard deviation). In addition to those measures find the min, max, count, percentile, and frequency distribution of the sample. You can create an object called statistics and create all the functions which do statistical calculations as method for the statistics object. Check the output below.
/*const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
console.log('Count:', statistics.count()) // 25
console.log('Sum: ', statistics.sum()) // 744
console.log('Min: ', statistics.min()) // 24
console.log('Max: ', statistics.max()) // 38
console.log('Range: ', statistics.range() // 14
console.log('Mean: ', statistics.mean()) // 30
console.log('Median: ',statistics.median()) // 29
console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5}
console.log('Variance: ',statistics.var()) // 17.5
console.log('Standard Deviation: ', statistics.std()) // 4.2
console.log('Variance: ',statistics.var()) // 17.5
console.log('Frequency Distribution: ',statistics.freqDist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)] */
const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
//1 count, sum, min, max, range
const statistics = {};
statistics.count = (arr) => arr.length;
statistics.sum = (arr) => arr.reduce((a, b) => a + b);
statistics.min = (arr) => Math.min(...arr);
statistics.max = (arr) => Math.max(...arr);
statistics.range = (arr) => Math.max(...arr) - Math.min(...arr);
//2 mean : an average of a data setPermalink
statistics.mean = (arr) => {
const sum = arr.reduce((a, b) => a + b);
const count = arr.length;
// need to return explicitly
return Math.round(sum / count);
}
console.log('Mean: ', statistics.mean(ages));
//3. median : the middle value when a data set is sorted
statistics.median = (arr) => {
let median;
const sortedArr = arr.sort((a, b) => a - b);
if (arr.length % 2 != 0) {
median = sortedArr[(arr.length - 1) / 2];
} else {
median = (sortedArr[(arr.length / 2) - 1] + sortedArr[arr.length / 2]) / 2;
}
return median;
}
console.log('Median: ',statistics.median(ages));
//4. mode : the most common number in a set
statistics.mode = (arr) => {
const num = [...new Set(arr)];
const count = num.map((element) =>
arr.filter((number) => number === element).length)
let max = Math.max(...count);
let object = {};
object.mode = num[count.indexOf(max)];
object.count = max;
return object;
}
console.log('Mode: ', statistics.mode(ages));
//5. variance
//1) Find a mean.
//2) Find each scores deviation from the mean.
//3) Square each deviation from the mean.
//4) Find the sum of squares.
//5) Divide the sum of squares by n-1(sample) or N(population).
//+) A population is the entire group that you want to draw conclusions about. A sample is the specific group that you will collect data from. The size of the sample is always less than the total size of the population.
statistics.var = (arr) => {
const sum = arr.reduce((a, b) => a + b);
const count = arr.length;
const mean = sum / count;
const deviation = arr.map((element) => element - mean);
const square = deviation.map((num) => num * num);
const sumOfSquares = square.reduce((a, b) => a + b);
return +(sumOfSquares / count).toFixed(1);
}
console.log('Variance: ',statistics.var(ages));
//6. standard deviation
//Basically its a square-rooted variance.
//1) Find a mean. 2) For each data point, find the square of its distance to the mean. 3) Sum the values from Step 2. 4) Divide by the number of data points. 5) Take the square root.
statistics.std = (arr) => {
const sum = arr.reduce((a, b) => a + b);
const count = arr.length;
const mean = sum / count;
const deviation = arr.map((element) => element - mean);
const square = deviation.map((num) => num * num);
const sumOfSquares = square.reduce((a, b) => a + b);
const variance = sumOfSquares / count;
return +(Math.sqrt(variance).toFixed(1));
}
console.log('Standard Deviation: ', statistics.std(ages)); // 4.2
//7. frequency distribution
//1) Calculate the range of the data set.
//2) Divide the range by the number of groups you want and then round up.
//3) Use the class width to create your groups.
//4) Find the frequency for each group.
statistics.frecDistibution = function (arr) {
const num = [...new Set(arr)];
const freqDist = [];
num.forEach((unique) => {
let frequency;
let times = arr.filter((element) =>
element === unique).length;
frequency = `(${(times / arr.length) * 100}, ${unique})`;
freqDist.push(frequency);
})
return statistics['frequency distribution'] = [freqDist.join(', ')];
}
console.log(statistics.frecDistibution(ages))
console.log(statistics.std(ages))

@ -45,7 +45,7 @@
## Set
Set is a collection of elements. Set can only contains unique elements.
Lets see how to create a set
Let us see how to create a set in the section below.
### Creating an empty set
@ -55,7 +55,7 @@ console.log(companies)
```
```sh
{}
Set(0) {}
```
### Creating set from array
@ -117,7 +117,6 @@ companies.add('Facebook')
companies.add('Amazon')
companies.add('Oracle')
companies.add('Microsoft')
console.log(companies.size) // 5 elements in the set
console.log(companies)
```
@ -165,13 +164,11 @@ It removes all the elements from a set.
```js
companies.clear()
console.log(companies)
```
```sh
{}
Set(0) {}
```
See the example below to learn how to use set.
@ -202,7 +199,7 @@ console.log(counts)
```
```js
;[
[
{ lang: 'English', count: 3 },
{ lang: 'Finnish', count: 1 },
{ lang: 'French', count: 2 },
@ -345,7 +342,7 @@ Helsinki
### Checking key in Map
Check if a key exist in a map using _has_ method. It returns _true_ or _false_.
Check if a key exists in a map using _has_ method. It returns _true_ or _false_.
```js
console.log(countriesMap.has('Finland'))
@ -371,7 +368,7 @@ for (const country of countriesMap) {
```js
for (const [country, city] of countriesMap){
console.log(country, city)
console.log(country, city)
}
```
@ -438,8 +435,6 @@ const countries = ['Finland', 'Sweden', 'Norway']
]
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 9](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) | [Day 11 >>](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md)

@ -18,23 +18,23 @@
![Day 11](../images/banners/day_1_11.png)
- [Day 11](#day-11)
- [Destructuring and Spread](#destructuring-and-spread)
- [Destructing Arrays](#destructing-arrays)
- [Destructuring during iteration](#destructuring-during-iteration)
- [Destructuring Object](#destructuring-object)
- [Renaming during structuring](#renaming-during-structuring)
- [Object parameter without destructuring](#object-parameter-without-destructuring)
- [Object parameter with destructuring](#object-parameter-with-destructuring)
- [Destructuring object during iteration](#destructuring-object-during-iteration)
- [Spread or Rest Operator](#spread-or-rest-operator)
- [Spread operator to get the rest of array elements](#spread-operator-to-get-the-rest-of-array-elements)
- [Spread operator to copy array](#spread-operator-to-copy-array)
- [Spread operator to copy object](#spread-operator-to-copy-object)
- [Spread operator with arrow function](#spread-operator-with-arrow-function)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
- [Destructuring and Spread](#destructuring-and-spread)
- [Destructing Arrays](#destructing-arrays)
- [Destructuring during iteration](#destructuring-during-iteration)
- [Destructuring Object](#destructuring-object)
- [Renaming during structuring](#renaming-during-structuring)
- [Object parameter without destructuring](#object-parameter-without-destructuring)
- [Object parameter with destructuring](#object-parameter-with-destructuring)
- [Destructuring object during iteration](#destructuring-object-during-iteration)
- [Spread or Rest Operator](#spread-or-rest-operator)
- [Spread operator to get the rest of array elements](#spread-operator-to-get-the-rest-of-array-elements)
- [Spread operator to copy array](#spread-operator-to-copy-array)
- [Spread operator to copy object](#spread-operator-to-copy-object)
- [Spread operator with arrow function](#spread-operator-with-arrow-function)
- [Exercises](#exercises)
- [Exercises: Level 1](#exercises-level-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises: Level 3](#exercises-level-3)
# Day 11
@ -108,7 +108,7 @@ If we like to skip on of the values in the array we use additional comma. The co
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
let [, secondPerson, , fourthPerson] = name // first and third person is omitted
let [, secondPerson, , fourthPerson] = names // first and third person is omitted
console.log(secondPerson, fourthPerson)
```
@ -218,7 +218,7 @@ console.log(w, h, a, p)
20 10 200 undefined
```
If the key is not found in the object the variable will be assigned to undefined. In case, the key is not in the object we can give a default value during declaration. See the example.
If the key is not found in the object the variable will be assigned to undefined. Sometimes the key might not be in the object, in that case we can give a default value during declaration. See the example.
```js
const rectangle = {
@ -229,7 +229,7 @@ const rectangle = {
let { width, height, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //20 10 200 60
//Lets modify the object:width to 30 and perimeter to 80
//Let us modify the object:width to 30 and perimeter to 80
```
```js
@ -243,7 +243,7 @@ let { width, height, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //30 10 200 80
```
Destructuring keys as a function parameters. Lets create a function which take a rectangle object and it return a perimeter of a rectangle.
Destructuring keys as a function parameters. Let us create a function which takes a rectangle object and it returns a perimeter of a rectangle.
### Object parameter without destructuring
@ -282,7 +282,7 @@ const person = {
],
languages: ['Amharic', 'English', 'Suomi(Finnish)']
}
// Lets create a function which give information about the person object without destructuring
// Let us create a function which give information about the person object without destructuring
const getPersonInfo = obj => {
const skills = obj.skills
@ -314,7 +314,7 @@ console.log(calculatePerimeter(rect)) // 60
```
```js
// Lets create a function which give information about the person object with destructuring
// Let us create a function which give information about the person object with destructuring
const getPersonInfo = ({
firstName,
lastName,
@ -335,7 +335,7 @@ const getPersonInfo = ({
}
console.log(getPersonInfo(person))
/*
Asabeneh Yetayeh lives in Finland. He is 200 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)
Asabeneh Yetayeh lives in Finland. He is 250 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)
*/
```
@ -373,7 +373,7 @@ Assess Test Result 4/1/2020 1:00 false
### Spread or Rest Operator
When we destructure an array we use the spread operator(...) to get the rest elements as array. In addition to that we use spread operator to spread arr elements to another array.
When we destructure an array we use the spread operator(...) to get the rest elements as array. In addition to that we use spread operator to spread array elements to another array.
### Spread operator to get the rest of array elements
@ -499,7 +499,7 @@ const sumAllNums = (...args) => {
console.log(args)
}
sumAllNums(1, 2, 3,4,5)
sumAllNums(1, 2, 3, 4, 5)
```
@ -519,7 +519,7 @@ const sumAllNums = (...args) => {
}
console.log(sumAllNums(1, 2, 3,4,5))
console.log(sumAllNums(1, 2, 3, 4, 5))
```
```sh
@ -597,7 +597,6 @@ const users = [
1. Iterate through the users array and get all the keys of the object using destructuring
2. Find the persons who have less than two skills
### Exercises: Level 3
1. Destructure the countries object print name, capital, population and languages of all countries
@ -613,7 +612,7 @@ const users = [
```
3. Write a function called *convertArrayToObject* which can convert the array to a structure object.
```js
const students = [
['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]],
@ -693,6 +692,7 @@ const users = [
}
```
🎉 CONGRATULATIONS ! 🎉
[<< Day 10](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | [Day 12 >>](../12_Day_Regular_expressions/12_day_regular_expressions.md)
[<< Day 10](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | [Day 12 >>](../12_Day_Regular_expressions/12_day_regular_expressions.md)

@ -60,9 +60,9 @@ A pattern could be a text or any form of pattern which some sort of similarity.
#### Flags
Flags are optional parameters in a regular expression which determine the type of searching. Let see some of the flags:
Flags are optional parameters in a regular expression which determine the type of searching. Let us see some of the flags:
- g:is a global flag which means looking for a pattern in whole text
- g: a global flag which means looking for a pattern in whole text
- i: case insensitive flag(it searches for both lowercase and uppercase)
- m: multiline
@ -106,7 +106,7 @@ let regEx= new RegExp('love','gi')
### RegExpp Object Methods
Let see some of RegExp methods
Let us see some of RegExp methods
#### Testing for a match
@ -227,7 +227,7 @@ I am teacher and I love teaching.There is nothing as more rewarding as educatin
* [0-9] means any number 0 to 9
* [A-Za-z0-9] any character which is a to z, A to Z, 0 to 9
* \\: uses to escape special characters
* \d mean:match where the string contains digits (numbers from 0-9)
* \d mean: match where the string contains digits (numbers from 0-9)
* \D mean: match where the string does not contain digits
* . : any character except new line character(\n)
* ^: starts with
@ -236,13 +236,14 @@ I am teacher and I love teaching.There is nothing as more rewarding as educatin
* $: ends with
* r'substring$' eg r'love$', sentence ends with a word love
* *: zero or more times
* r'[a]*' means a optional or it can be occur many times.
* r'[a]*' means a optional or it can occur many times.
* +: one or more times
* r'[a]+' mean at least once or more times
* r'[a]+' means at least once or more times
* ?: zero or one times
* r'[a]?' mean zero times or once
* r'[a]?' means zero times or once
* \b: word bounder, matches with the beginning or ending of a word
* {3}: Exactly 3 characters
* {3,}: At least 3 character
* {3,}: At least 3 characters
* {3,8}: 3 to 8 characters
* |: Either or
* r'apple|banana' mean either of an apple or a banana
@ -257,20 +258,20 @@ Let's use example to clarify the above meta characters
Let's use square bracket to include lower and upper case
```js
const pattern = '[Aa]pple' // this square bracket mean either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
const pattern = '[Aa]pple' // this square bracket means either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day keeps the doctor way has been replaced by a banana a day keeps the doctor far far away. '
const matches = txt.match(pattern)
console.log(matches)
```
```sh
["Apple", index: 0, input: "Apple and banana are fruits. An old cliche says an…by a banana a day keeps the doctor far far away. ", groups: undefined]
["Apple", index: 0, input: "Apple and banana are fruits. An old cliche says an apple a day keeps the doctor way has been replaced by a banana a day keeps the doctor far far away.", groups: undefined]
```
```js
const pattern = /[Aa]pple/g // this square bracket mean either A or a
const pattern = /[Aa]pple/g // this square bracket means either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
const matches = txt.match(pattern)
@ -344,7 +345,7 @@ console.log(matches) // ['and banana are fruits']
### Zero or more times(*)
Zero or many times. The pattern could may not occur or it can occur many times.
Zero or many times. The pattern may not occur or it can occur many times.
```js
@ -358,7 +359,7 @@ console.log(matches) // ['and banana are fruits']
### Zero or one times(?)
Zero or one times. The pattern could may not occur or it may occur once.
Zero or one times. The pattern may not occur or it may occur once.
```js
const txt = 'I am not sure if there is a convention how to write the word e-mail.\
@ -372,11 +373,25 @@ console.log(matches) // ["e-mail", "email", "Email", "E-mail"]
### Quantifier in RegExp
We can specify the length of the substring we look for in a text, using a curly bracket. Lets imagine, we are interested in substring that their length are 4 characters
We can specify the length of the substring we look for in a text, using a curly bracket. Let us see, how ot use RegExp quantifiers. Imagine, we are interested in substring that their length are 4 characters
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\\b\w{4}\b/g // exactly four character words
const matches = txt.match(pattern)
console.log(matches) //['This', 'made', '2019']
```
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\b[a-zA-Z]{4}\b/g // exactly four character words without numbers
const matches = txt.match(pattern)
console.log(matches) //['This', 'made']
```
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\d{4}/g // exactly four times
const pattern = /\d{4}/g // a number and exactly four digits
const matches = txt.match(pattern)
console.log(matches) // ['2019']
```
@ -403,7 +418,7 @@ console.log(matches) // ['This']
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /[^A-Za-z,. ]+/g // ^ in set character means negation, not A to Z, not a to z, no space, no coma no period
const pattern = /[^A-Za-z,. ]+/g // ^ in set character means negation, not A to Z, not a to z, no space, no comma no period
const matches = txt.match(pattern)
console.log(matches) // ["6", "2019"]
```

@ -19,21 +19,21 @@
![Thirty Days Of JavaScript](../images/banners/day_1_13.png)
- [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)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises:Level 2](#exerciseslevel-2)
- [Exercises:Level 3](#exerciseslevel-3)
- [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)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises:Level 2](#exerciseslevel-2)
- [Exercises:Level 3](#exerciseslevel-3)
# Day 13
@ -43,7 +43,7 @@ In this section, we will cover about console and console object methods. Absolut
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 methods.
In addition to the famous, console.log() method, the console provides other more methods.
### console.log()
@ -99,7 +99,7 @@ console.warn('Warning is different from error')
### console.error()
The console.error() methods shows an error messages.
The console.error() method shows an error messages.
```js
console.error('This is an error message')
@ -224,7 +224,7 @@ According the above output the regular for loop is slower than for of or forEach
### console.info()
It display information message on browser console.
It displays information message on browser console.
```js
console.info('30 Days Of JavaScript challenge is trending on Github')
@ -312,7 +312,7 @@ console.groupEnd()
### console.count()
It prints the number of time this 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
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 = () => {

@ -586,7 +586,7 @@ Asabeneh Yetayeh is Finland. He lives Helsinki, 250.
### Overriding methods
As you can see, we manage to access all the methods in the Person Class and we used it in the Student child class. We can customize the parent methods, we can add additional properties to a child class. If we want to customize, the methods and if we want to add extra properties, we need to use the constructor function the child class too. In side the constructor function we call the super() function to access all the properties from the parent class. The Person class didn't have gender but now let us give gender property for the child class, Student. If the same method name used in the child class, the parent method will be overridden.
As you can see, we manage to access all the methods in the Person Class and we used it in the Student child class. We can customize the parent methods, we can add additional properties to a child class. If we want to customize, the methods and if we want to add extra properties, we need to use the constructor function the child class too. Inside the constructor function we call the super() function to access all the properties from the parent class. The Person class didn't have gender but now let us give gender property for the child class, Student. If the same method name used in the child class, the parent method will be overridden.
```js
class Student extends Person {

@ -197,7 +197,7 @@ square(2)
Promise {<resolved>: 4}
```
The word _async_ in front of a function means that function will return a promise. The above square function instead of a value it returned a promise.
The word _async_ in front of a function means that function will return a promise. The above square function instead of a value it returns a promise.
How do we access the value from the promise? To access the value from the promise, we will use the keyword _await_.
@ -206,6 +206,7 @@ const square = async function (n) {
return n * n
}
const value = await square(2)
console.log(value)
```
```sh

@ -135,13 +135,13 @@ The _document.querySelector_ method can select an HTML or HTML elements by tag n
```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 h1 element with class title
let firstTitle = document.querySelector('.title') // select the first available element with class title
```
**_querySelectorAll_**: can be used to select html element by its tag name or class. It return a nodeList which is an array like object which support array methods. We can use **_for loop_** or **_forEach_** to loop through each nodeList elements.
**_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')
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++) {
@ -351,7 +351,7 @@ As you have notice, the properties of css when we use it in JavaScript is going
### Exercise: Level 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 get each of the the paragraph using **_document.querySelector('#id')_** and by their id
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_**

@ -16,12 +16,14 @@
<div>
<small>Support [**Asabeneh**](https://www.patreon.com/asabeneh?fan_landing=true) to create more educational materials</small>
</div>
[<< Day 29](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md)
<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)
![Thirty Days Of JavaScript](../images/banners/day_1_30.png)
@ -31,6 +33,7 @@
- [Exercise: Level 2](#exercise-level-2)
- [Exercise: Level 3](#exercise-level-3)
- [Testimony](#testimony)
- [Support](#support)
# Day 30
@ -45,9 +48,8 @@
2. Validate the following form using regex.
![form validation](./../images/projects/dom_mini_project_form_validation_day_10.2.1.png)
![form validation](./../images/projects/dom_mini_project_form_validation_day_10.2.png)
![form validation](./../images/projects/dom_mini_project_form_validation_day_10.2.png)
### Exercise: Level 2
@ -57,8 +59,14 @@
## Testimony
Now it is time to express your thoughts about the Author and 30DaysOfJavaScript. You can leave your testimonial on this [link](https://testimonify.herokuapp.com/)
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
[![paypal](../images/paypal_lg.png)](https://www.paypal.me/asabeneh)
~![Congratulations](./../images/projects/congratulations.gif)
![Congratulations](./../images/projects/congratulations.gif)
[<< Day 29](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md)

@ -0,0 +1,980 @@
<div align="center">
<h1> 30 Days Of JavaScript: Data Types</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>
[<< Giorno 1](../readMe.md) | [Giorno 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)
![Thirty Days Of JavaScript](../../images/banners/day_1_2.png)
- [📔 Giorno 2](#-day-2)
- [Tipi di Dati](#data-types)
- [Tipi di Dati Primitivi](#primitive-data-types)
- [Tipi di Dati Non Primitivi](#non-primitive-data-types)
- [Numbers](#numbers)
- [Dichiarare un Tipo Number](#declaring-number-data-types)
- [L'Oggetto Math](#math-object)
- [Random Number Generator](#random-number-generator)
- [Strings](#strings)
- [Concatenare Stringhe](#string-concatenation)
- [Concatenare Usando l'Operatore Addizione](#concatenating-using-addition-operator)
- [Stringe Letterali Lunghe](#long-literal-strings)
- [Sequenze di Escape nelle Stringhe](#escape-sequences-in-strings)
- [Stringhe Parametriche (Template Strings)](#template-literals-template-strings)
- [Metodi del Tipo String](#string-methods)
- [Verificare il Ripo di Dato ed Eseguire Casting](#checking-data-types-and-casting)
- [Verificare il Tipo di Dato](#checking-data-types)
- [Cambiare il Tipo di Dato (Casting)](#changing-data-type-casting)
- [Da String a Int](#string-to-int)
- [Da String a Float](#string-to-float)
- [Da Float a Int](#float-to-int)
- [💻 Giorno 2: Esercizi](#-day-2-exercises)
- [Esercizi: Livello 1](#exercise-level-1)
- [Esercizi: Livello 2](#exercise-level-2)
- [Esercizi: Livello 3](#exercises-level-3)
# 📔 Giorno 2
## Tipi di Dati
Nella sezione precedente abbiamo parlato un po' dei tipi di dati. I dati o i valori hanno tipi di dati. I tipi di dati descrivono le caratteristiche dei dati. I tipi di dati possono essere suddivisi in due categorie:
1. Tipi di Dati Primitivi
2. Tipi di Dati Non Primitivi (Object References)
### Tipi di Dati Primitivi
I tipi di dati primitivi in JavaScript includono:
1. Numbers - Interi, float
2. Strings - Qualsiasi dato tra virgolette singole, virgolette doppie o virgolette rovesciate.
3. Boolean - valore vero o falso
4. Null - valore vuoto o nessun valore
5. Undefined - una variabile dichiarata senza valore
6. Symbol - Un valore unico che può essere generato dal costruttore Symbol.
I tipi di dati non primitivi in JavaScript includono:
1. Objects
2. Arrays
Vediamo ora cosa significano esattamente i tipi di dati primitivi e non primitivi.
I tipi di dati *primitivi* sono tipi di dati immutabili (non modificabili). Una volta creato un tipo di dati primitivo, non è possibile modificarlo.
**Esempio:**
```js
let word = 'JavaScript'
```
Se si tenta di modificare la stringa memorizzata nella variabile *word*, JavaScript dovrebbe sollevare un errore. Qualsiasi tipo di dato sotto una virgoletta singola, una doppia virgoletta o una virgola rovesciata è un tipo di dato stringa.
```js
word[0] = 'Y'
```
Questa espressione non modifica la stringa memorizzata nella variabile *word*. Quindi, possiamo dire che le stringhe non sono modificabili o, in altre parole, immutabili.
I tipi di dati primitivi vengono confrontati in base ai loro valori. Confrontiamo diversi valori di dati. Si veda l'esempio seguente:
```js
let numOne = 3
let numTwo = 3
console.log(numOne == numTwo) // true
let js = 'JavaScript'
let py = 'Python'
console.log(js == py) //false
let lightOn = true
let lightOff = false
console.log(lightOn == lightOff) // false
```
### Tipi di dati non primitivi
I tipi di dati *non primitivi* sono modificabili o mutabili. È possibile modificare il valore dei tipi di dati non primitivi dopo la loro creazione.
Vediamo come creare un array. Una matrice è un elenco di valori di dati in una parentesi quadra. Gli array possono contenere lo stesso tipo di dati o tipi diversi. I valori degli array sono referenziati dal loro indice. In JavaScript l'indice dell'array inizia da zero. Cioè, il primo elemento di un array si trova all'indice zero, il secondo elemento all'indice uno, il terzo elemento all'indice due e così via.
```js
let nums = [1, 2, 3]
nums[0] = 10
console.log(nums) // [10, 2, 3]
```
Come si può notare, un array, che è un tipo di dati non primitivo, è mutabile. I tipi di dati non primitivi non possono essere confrontati per valore. Anche se due tipi di dati non primitivi hanno le stesse proprietà e gli stessi valori, non sono strettamente uguali.
```js
let nums = [1, 2, 3]
let numbers = [1, 2, 3]
console.log(nums == numbers) // false
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
let userTwo = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
console.log(userOne == userTwo) // false
```
Regola generale: non si confrontano tipi di dati non primitivi. Non si confrontano array, funzioni o oggetti.
I valori non primitivi vengono definiti tipi di riferimento, perché vengono confrontati in base al riferimento anziché al valore. Due oggetti sono strettamente uguali solo se fanno riferimento allo stesso oggetto sottostante.
```js
let nums = [1, 2, 3]
let numbers = nums
console.log(nums == numbers) // true
let userOne = {
name:'Asabeneh',
role:'teaching',
country:'Finland'
}
let userTwo = userOne
console.log(userOne == userTwo) // true
```
Se avete difficoltà a capire la differenza tra tipi di dati primitivi e non primitivi, non siete gli unici. Calmatevi, passate alla sezione successiva e provate a tornare dopo qualche tempo. Ora iniziamo i tipi di dati con il tipo di numero.
## Numbers
I numeri sono valori interi e decimali che possono eseguire tutte le operazioni aritmetiche.
Vediamo alcuni esempi di numeri.
### Dichiarare i tipi di dati numerici
```js
let age = 35
const gravity = 9.81 // we use const for non-changing values, gravitational constant in m/s2
let mass = 72 // mass in Kilogram
const PI = 3.14 // pi a geometrical constant
// More Esempios
const boilingPoint = 100 // temperature in oC, boiling point of water which is a constant
const bodyTemp = 37 // oC average human body temperature, which is a constant
console.log(age, gravity, mass, PI, boilingPoint, bodyTemp)
```
### L'Oggetto Math
In JavaScript l'oggetto Math fornisce molti metodi per lavorare con i numeri.
```js
const PI = Math.PI
console.log(PI) // 3.141592653589793
// Rounding to the closest number
// if above .5 up if less 0.5 down rounding
console.log(Math.round(PI)) // 3 to round values to the nearest number
console.log(Math.round(9.81)) // 10
console.log(Math.floor(PI)) // 3 rounding down
console.log(Math.ceil(PI)) // 4 rounding up
console.log(Math.min(-5, 3, 20, 4, 5, 10)) // -5, returns the minimum value
console.log(Math.max(-5, 3, 20, 4, 5, 10)) // 20, returns the maximum value
const randNum = Math.random() // creates random number between 0 to 0.999999
console.log(randNum)
// Let us create random number between 0 to 10
const num = Math.floor(Math.random () * 11) // creates random number between 0 and 10
console.log(num)
//Absolute value
console.log(Math.abs(-10)) // 10
//Square root
console.log(Math.sqrt(100)) // 10
console.log(Math.sqrt(2)) // 1.4142135623730951
// Power
console.log(Math.pow(3, 2)) // 9
console.log(Math.E) // 2.718
// Logarithm
// Returns the natural logarithm with base E of x, Math.log(x)
console.log(Math.log(2)) // 0.6931471805599453
console.log(Math.log(10)) // 2.302585092994046
// Returns the natural logarithm of 2 and 10 respectively
console.log(Math.LN2) // 0.6931471805599453
console.log(Math.LN10) // 2.302585092994046
// Trigonometry
Math.sin(0)
Math.sin(60)
Math.cos(0)
Math.cos(60)
```
#### Random Number Generator
L'oggetto JavaScript Math ha un generatore di numeri con il metodo random() che genera numeri da 0 a 0,9999999...
```js
let randomNum = Math.random() // generates 0 to 0.999...
```
Vediamo ora come utilizzare il metodo random() per generare un numero casuale compreso tra 0 e 10:
```js
let randomNum = Math.random() // generates 0 to 0.999
let numBtnZeroAndTen = randomNum * 11
console.log(numBtnZeroAndTen) // this gives: min 0 and max 10.99
let randomNumRoundToFloor = Math.floor(numBtnZeroAndTen)
console.log(randomNumRoundToFloor) // this gives between 0 and 10
```
## Strings
Le stringhe sono testi, che si trovano sotto le virgolette **_singole_**, **_doppie_**, **_back-tick_**. Per dichiarare una stringa, abbiamo bisogno di un nome di variabile, di un operatore di assegnazione, di un valore tra virgolette singole, virgolette doppie o virgolette back-tick.
```js
let space = ' ' // an empty space string
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let quote = "The saying,'Seeing is Believing' is not correct in 2020."
let quotWithBackTick = `The saying,'Seeing is Believing' is not correct in 2020.`
```
### Concatenazione di Stringhe
Il collegamento di due o più stringhe tra loro si chiama concatenazione.
Utilizzando le stringhe dichiarate nella precedente sezione:
```js
let fullName = firstName + space + lastName; // concatenation, merging two string together.
console.log(fullName);
```
```sh
Asabeneh Yetayeh
```
Possiamo concatenare le stringhe in diversi modi.
#### Concatenare Usando l'Operatore Addizione
La concatenazione con l'operatore di addizione è un vecchio metodo. Questo modo di concatenare è noioso e soggetto ad errori. È bene sapere come concatenare in questo modo, ma suggerisco vivamente di usare le stringhe modello ES6 (spiegate più avanti).
```js
// Declaring different variables of different data types
let space = ' '
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let age = 250
let fullName =firstName + space + lastName
let personInfoOne = fullName + '. I am ' + age + '. I live in ' + country; // ES5 string addition
console.log(personInfoOne)
```
```sh
Asabeneh Yetayeh. I am 250. I live in Finland
```
#### Stringhe Letterali Lunghe
Una stringa può essere un singolo carattere, un paragrafo o una pagina. Se la lunghezza della stringa è eccessiva, non può essere contenuta in una riga. Possiamo usare il carattere backslash (\) alla fine di ogni riga per indicare che la stringa continuerà sulla riga successiva.
**Esempio:**
```js
const paragraph = "My name is Asabeneh Yetayeh. I live in Finland, Helsinki.\
I am a teacher and I love teaching. I teach HTML, CSS, JavaScript, React, Redux, \
Node.js, Python, Data Analysis and D3.js for anyone who is interested to learn. \
In the end of 2019, I was thinking to expand my teaching and to reach \
to global audience and I started a Python challenge from November 20 - December 19.\
It was one of the most rewarding and inspiring experience.\
Now, we are in 2020. I am enjoying preparing the 30DaysOfJavaScript challenge and \
I hope you are enjoying too."
console.log(paragraph)
```
#### Escape Sequences nelle Stringhe
In JavaScript e in altri linguaggi di programmazione il carattere \ seguito da alcuni caratteri è una sequenza di escape. Vediamo i caratteri di escape più comuni:
- \n: new line
- \t: Tab, means 8 spaces
- \\\\: Back slash
- \\': Single quote (')
- \\": Double quote (")
```js
console.log('I hope everyone is enjoying the 30 Days Of JavaScript challenge.\nDo you ?') // line break
console.log('Days\tTopics\tEsercizios')
console.log('Day 1\t3\t5')
console.log('Day 2\t3\t5')
console.log('Day 3\t3\t5')
console.log('Day 4\t3\t5')
console.log('This is a backslash symbol (\\)') // To write a backslash
console.log('In every programming language it starts with \"Hello, World!\"')
console.log("In every programming language it starts with \'Hello, World!\'")
console.log('The saying \'Seeing is Believing\' isn\'t correct in 2020')
```
Output in console:
```sh
I hope everyone is enjoying the 30 Days Of JavaScript challenge.
Do you ?
Days Topics Esercizios
Day 1 3 5
Day 2 3 5
Day 3 3 5
Day 4 3 5
This is a backslash symbol (\)
In every programming language it starts with "Hello, World!"
In every programming language it starts with 'Hello, World!'
The saying 'Seeing is Believing' isn't correct in 2020
```
#### Stringhe Parametriche (Template Strings)
Per creare una stringa modello, utilizziamo due back-tick. Possiamo iniettare dati come espressioni all'interno di una stringa modello. Per iniettare dati, si racchiude l'espressione con una parentesi graffa ({}) preceduta dal segno $. Si veda la sintassi qui sotto.
```js
//Syntax
`String literal text`
`String literal text ${expression}`
```
**Esempio: 1**
```js
console.log(`The sum of 2 and 3 is 5`) // statically writing the data
let a = 2
let b = 3
console.log(`The sum of ${a} and ${b} is ${a + b}`) // injecting the data dynamically
```
**Esempio:2**
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
let language = 'JavaScript'
let job = 'teacher'
let age = 250
let fullName = firstName + ' ' + lastName
let personInfoTwo = `I am ${fullName}. I am ${age}. I live in ${country}.` //ES6 - String interpolation method
let personInfoThree = `I am ${fullName}. I live in ${city}, ${country}. I am a ${job}. I teach ${language}.`
console.log(personInfoTwo)
console.log(personInfoThree)
```
```sh
I am Asabeneh Yetayeh. I am 250. I live in Finland.
I am Asabeneh Yetayeh. I live in Helsinki, Finland. I am a teacher. I teach JavaScript.
```
Utilizzando un modello di stringa o un metodo di interpolazione delle stringhe, si possono aggiungere espressioni, che possono essere un valore o alcune operazioni (confronto, operazioni aritmetiche, operazioni ternarie).
```js
let a = 2
let b = 3
console.log(`${a} is greater than ${b}: ${a > b}`)
```
```sh
2 is greater than 3: false
```
### Medoti del Tipo String
Tutto in JavaScript è un oggetto. Una stringa è un tipo di dati primitivo, il che significa che non è possibile modificarla una volta creata. L'oggetto stringa ha molti metodi per le stringhe. Esistono diversi metodi per le stringhe che possono aiutarci a lavorare con le stringhe.
1. *length*: Il metodo stringa *length* restituisce il numero di caratteri di una stringa inclusi gli spazi vuoti.
**Esempio:**
```js
let js = 'JavaScript'
console.log(js.length) // 10
let firstName = 'Asabeneh'
console.log(firstName.length) // 8
```
2. *Accedere ai caratteri di una stringa*: È possibile accedere a ciascun carattere di una stringa utilizzando il suo indice. Nella programmazione, il conteggio inizia da 0. Il primo indice della stringa è zero e l'ultimo indice è la lunghezza della stringa meno uno.
![Accessing sting by index](../../images/string_indexes.png)
Accediamo ai diversi caratteri della stringa 'JavaScript'.
```js
let string = 'JavaScript'
let firstLetter = string[0]
console.log(firstLetter) // J
let secondLetter = string[1] // a
let thirdLetter = string[2]
let lastLetter = string[9]
console.log(lastLetter) // t
let lastIndex = string.length - 1
console.log(lastIndex) // 9
console.log(string[lastIndex]) // t
```
3. *toUpperCase()*: questo metodo cambia la stringa in lettere maiuscole.
```js
let string = 'JavaScript'
console.log(string.toUpperCase()) // JAVASCRIPT
let firstName = 'Asabeneh'
console.log(firstName.toUpperCase()) // ASABENEH
let country = 'Finland'
console.log(country.toUpperCase()) // FINLAND
```
4. *toLowerCase()*: questo metodo cambia la stringa in lettere minuscole.
```js
let string = 'JavasCript'
console.log(string.toLowerCase()) // javascript
let firstName = 'Asabeneh'
console.log(firstName.toLowerCase()) // asabeneh
let country = 'Finland'
console.log(country.toLowerCase()) // finland
```
5. *substr()*: Richiede due argomenti, l'indice iniziale e il numero di caratteri da tagliare.
```js
let string = 'JavaScript'
console.log(string.substr(4,6)) // Script
let country = 'Finland'
console.log(country.substr(3, 4)) // land
```
6. *substring()*: Richiede due argomenti, l'indice iniziale e l'indice finale, ma non include il carattere all'indice finale.
```js
let string = 'JavaScript'
console.log(string.substring(0,4)) // Java
console.log(string.substring(4,10)) // Script
console.log(string.substring(4)) // Script
let country = 'Finland'
console.log(country.substring(0, 3)) // Fin
console.log(country.substring(3, 7)) // land
console.log(country.substring(3)) // land
```
7. *split()*: Il metodo split divide una stringa in un punto specificato.
```js
let string = '30 Days Of JavaScript'
console.log(string.split()) // Changes to an array -> ["30 Days Of JavaScript"]
console.log(string.split(' ')) // Split to an array at space -> ["30", "Days", "Of", "JavaScript"]
let firstName = 'Asabeneh'
console.log(firstName.split()) // Change to an array - > ["Asabeneh"]
console.log(firstName.split('')) // Split to an array at each letter -> ["A", "s", "a", "b", "e", "n", "e", "h"]
let countries = 'Finland, Sweden, Norway, Denmark, and Iceland'
console.log(countries.split(',')) // split to any array at comma -> ["Finland", " Sweden", " Norway", " Denmark", " and Iceland"]
console.log(countries.split(', ')) //  ["Finland", "Sweden", "Norway", "Denmark", "and Iceland"]
```
8. *trim()*: Rimuove lo spazio di coda all'inizio o alla fine di una stringa.
```js
let string = ' 30 Days Of JavaScript '
console.log(string)
console.log(string.trim(' '))
let firstName = ' Asabeneh '
console.log(firstName)
console.log(firstName.trim()) // still removes spaces at the beginning and the end of the string
```
```sh
30 Days Of JavasCript
30 Days Of JavasCript
Asabeneh
Asabeneh
```
9. *includes()*: Prende un argomento di sottostringa e controlla se l'argomento di sottostringa esiste nella stringa. *include()* restituisce un booleano. Se una sottostringa esiste in una stringa, restituisce true, altrimenti restituisce false.
```js
let string = '30 Days Of JavaScript'
console.log(string.includes('Days')) // true
console.log(string.includes('days')) // false - it is case sensitive!
console.log(string.includes('Script')) // true
console.log(string.includes('script')) // false
console.log(string.includes('java')) // false
console.log(string.includes('Java')) // true
let country = 'Finland'
console.log(country.includes('fin')) // false
console.log(country.includes('Fin')) // true
console.log(country.includes('land')) // true
console.log(country.includes('Land')) // false
```
10. *replace()*: prende come parametro la vecchia sottostringa e una nuova sottostringa.
```js
string.replace(oldsubstring, newsubstring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.replace('JavaScript', 'Python')) // 30 Days Of Python
let country = 'Finland'
console.log(country.replace('Fin', 'Noman')) // Nomanland
```
11. *charAt()*: Prende l'indice e restituisce il valore in corrispondenza di quell'indice
```js
string.charAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charAt(0)) // 3
let lastIndex = string.length - 1
console.log(string.charAt(lastIndex)) // t
```
12. *charCodeAt()*: Prende l'indice e restituisce il codice char (numero ASCII) del valore in corrispondenza dell'indice.
```js
string.charCodeAt(index)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.charCodeAt(3)) // D ASCII number is 68
let lastIndex = string.length - 1
console.log(string.charCodeAt(lastIndex)) // t ASCII is 116
```
13. *indexOf()*: Prende una sottostringa e se la sottostringa esiste in una stringa restituisce la prima posizione della sottostringa se non esiste restituisce -1
```js
string.indexOf(substring)
```
```js
let string = '30 Days Of JavaScript'
console.log(string.indexOf('D')) // 3
console.log(string.indexOf('Days')) // 3
console.log(string.indexOf('days')) // -1
console.log(string.indexOf('a')) // 4
console.log(string.indexOf('JavaScript')) // 11
console.log(string.indexOf('Script')) //15
console.log(string.indexOf('script')) // -1
```
14. *lastIndexOf()*: Prende una sottostringa e se la sottostringa esiste in una stringa restituisce l'ultima posizione della sottostringa se non esiste restituisce -1
```js
//syntax
string.lastIndexOf(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.lastIndexOf('love')) // 67
console.log(string.lastIndexOf('you')) // 63
console.log(string.lastIndexOf('JavaScript')) // 38
```
15. *concat()*: prende molte sottostringhe e le unisce.
```js
string.concat(substring, substring, substring)
```
```js
let string = '30'
console.log(string.concat("Days", "Of", "JavaScript")) // 30DaysOfJavaScript
let country = 'Fin'
console.log(country.concat("land")) // Finland
```
16. *startsWith*: prende una sottostringa come argomento e verifica se la stringa inizia con la sottostringa specificata. Restituisce un booleano (vero o falso).
```js
//syntax
string.startsWith(substring)
```
```js
let string = 'Love is the best to in this world'
console.log(string.startsWith('Love')) // true
console.log(string.startsWith('love')) // false
console.log(string.startsWith('world')) // false
let country = 'Finland'
console.log(country.startsWith('Fin')) // true
console.log(country.startsWith('fin')) // false
console.log(country.startsWith('land')) // false
```
17. *endsWith*: prende una sottostringa come argomento e verifica se la stringa termina con la sottostringa specificata. Restituisce un booleano (vero o falso).
```js
string.endsWith(substring)
```
```js
let string = 'Love is the most powerful feeling in the world'
console.log(string.endsWith('world')) // true
console.log(string.endsWith('love')) // false
console.log(string.endsWith('in the world')) // true
let country = 'Finland'
console.log(country.endsWith('land')) // true
console.log(country.endsWith('fin')) // false
console.log(country.endsWith('Fin')) // false
```
18. *search*: prende come argomento una sottostringa e restituisce l'indice della prima corrispondenza. Il valore di ricerca può essere una stringa o un modello di espressione regolare.
```js
string.search(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.search('love')) // 2
console.log(string.search(/javascript/gi)) // 7
```
prende come argomento una sottostringa o un modello di espressione regolare e restituisce un array se c'è corrispondenza, altrimenti restituisce null. Vediamo come si presenta un modello di espressione regolare. Inizia con il segno / e termina con il segno /.
```js
let string = 'love'
let patternOne = /love/ // with out any flag
let patternTwo = /love/gi // g-means to search in the whole text, i - case insensitive
```
Match syntax
```js
// syntax
string.match(substring)
```
```js
let string = 'I love JavaScript. If you do not love JavaScript what else can you love.'
console.log(string.match('love'))
```
```sh
["love", index: 2, input: "I love JavaScript. If you do not love JavaScript what else can you love.", groups: undefined]
```
```js
let pattern = /love/gi
console.log(string.match(pattern)) // ["love", "love", "love"]
```
Estraiamo i numeri dal testo utilizzando un'espressione regolare. Questa non è la sezione delle espressioni regolari, niente panico! Tratteremo le espressioni regolari più avanti.
```js
let txt = 'In 2019, I ran 30 Days of Python. Now, in 2020 I am super exited to start this challenge'
let regEx = /\d+/
// d with escape character means d not a normal d instead acts a digit
// + means one or more digit numbers,
// if there is g after that it means global, search everywhere.
console.log(txt.match(regEx)) // ["2", "0", "1", "9", "3", "0", "2", "0", "2", "0"]
console.log(txt.match(/\d+/g)) // ["2019", "30", "2020"]
```
20. *repeat()*: prende come argomento un numero e restituisce la versione ripetuta della stringa.
```js
string.repeat(n)
```
```js
let string = 'love'
console.log(string.repeat(10)) // lovelovelovelovelovelovelovelovelovelove
```
## Verificiare i Tipi di Dati ed eseguire Casting
### Verificiare i Tipi di Dati
Per verificare il tipo di dati di una certa variabile si utilizza il metodo _typeof_.
**Esempio:**
```js
// Different javascript data types
// Let's declare different data types
let firstName = 'Asabeneh' // string
let lastName = 'Yetayeh' // string
let country = 'Finland' // string
let city = 'Helsinki' // string
let age = 250 // number, it is not my real age, do not worry about it
let job // undefined, because a value was not assigned
console.log(typeof 'Asabeneh') // string
console.log(typeof firstName) // string
console.log(typeof 10) // number
console.log(typeof 3.14) // number
console.log(typeof true) // boolean
console.log(typeof false) // boolean
console.log(typeof NaN) // number
console.log(typeof job) // undefined
console.log(typeof undefined) // undefined
console.log(typeof null) // object
```
### Cambiare il Tipo di Dato (Casting)
- Casting: Conversione di un tipo di dati in un altro tipo di dati. Utilizziamo _parseInt()_, _parseFloat()_, _Number()_, _+ sign_, _str()_.
Quando si eseguono operazioni aritmetiche, i numeri di stringa devono essere prima convertiti in numeri interi o float, altrimenti viene restituito un errore.
#### Da String a Int
Possiamo convertire un numero di stringa in un numero. Qualsiasi numero all'interno di un apice è un numero stringa. Un esempio di numero stringa: '10', '5', ecc.
Possiamo convertire una stringa in un numero utilizzando i seguenti metodi:
- parseInt()
- Number()
- Plus sign(+)
```js
let num = '10'
let numInt = parseInt(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = Number(num)
console.log(numInt) // 10
```
```js
let num = '10'
let numInt = +num
console.log(numInt) // 10
```
#### Da String a Float
Possiamo convertire un numero float stringa in un numero float. Qualsiasi numero float all'interno di una citazione è un numero float stringa. Un esempio di numero stringa float: '9,81', '3,14', '1,44', ecc.
È possibile convertire una stringa float in un numero utilizzando i seguenti metodi:
- parseFloat()
- Number()
- Plus sign(+)
```js
let num = '9.81'
let numFloat = parseFloat(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = Number(num)
console.log(numFloat) // 9.81
```
```js
let num = '9.81'
let numFloat = +num
console.log(numFloat) // 9.81
```
#### Da Float a Int
Possiamo convertire i numeri float in numeri interi.
Per convertire i float in int utilizziamo il metodo seguente:
- parseInt()
```js
let num = 9.81
let numInt = parseInt(num)
console.log(numInt) // 9
```
🌕 Fantastico. Hai appena completato le sfide del secondo giorno e sei due passi avanti sulla via della grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## 💻 Giorno 2: Esercizi
### Esercizio: Livello 1
1. Dichiarare una variabile chiamata sfida e assegnarle un valore iniziale **'30 Days Of JavaScript'**.
2. Stampate la stringa sulla console del browser usando __console.log()__.
3. Stampate la __lunghezza__ della stringa nella console del browser usando _console.log()_.
4. Cambiare tutti i caratteri della stringa in lettere maiuscole utilizzando il metodo __toUpperCase()__.
5. Cambiare tutti i caratteri della stringa in lettere minuscole usando il metodo __toLowerCase()__.
6. Tagliare (slice) la prima parola della stringa utilizzando il metodo __substr()__ o __substring()__.
7. Tagliare la frase *Giorni di JavaScript* da *30 Giorni di JavaScript*.
8. Verificare se la stringa contiene la parola __Script__ utilizzando il metodo __includes()__.
9. Dividere la __stringa__ in un __array__ usando il metodo __split()__.
10. Dividere la stringa 30 Days Of JavaScript nello spazio usando il metodo __split()__.
11. Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon" __split__ la stringa alla virgola e la trasforma in un array.
12. Cambiare 30 Days Of JavaScript in 30 Days Of Python usando il metodo __replace()__.
13. Qual è il carattere all'indice 15 nella stringa '30 giorni di JavaScript'? Usate il metodo __charAt()__.
14. Qual è il codice del carattere J nella stringa '30 Days Of JavaScript' usando il metodo __charCodeAt()__.
15. Usate __indexOf__ per determinare la posizione della prima occorrenza di __a__ in 30 Giorni Di JavaScript.
16. Usate __lastIndexOf__ per determinare la posizione dell'ultima occorrenza di __a__ in 30 Days Of JavaScript.
17. Usate __indexOf__ per trovare la posizione della prima occorrenza della parola __perché__ nella seguente frase:__"Non si può terminare una frase con perché perché perché è una congiunzione"__.
18. Usate __lastIndexOf__ per trovare la posizione dell'ultima occorrenza della parola __because__ nella seguente frase:__'Non si può concludere una frase con perché perché perché è una congiunzione'__.
19. Usare __search__ per trovare la posizione della prima occorrenza della parola __because__ nella seguente frase:__'Non si può terminare una frase con perché perché perché è una congiunzione'__
20. Usate __trim()__ per rimuovere gli spazi bianchi all'inizio e alla fine di una stringa, ad esempio ' 30 Days Of JavaScript '.
21. Usate il metodo __startsWith()__ con la stringa *30 Days Of JavaScript* e rendete il risultato vero.
22. Usate il metodo __endsWith()__ con la stringa *30 Days Of JavaScript* e fate in modo che il risultato sia vero.
23. Usare il metodo __match()__ per trovare tutti gli __a__ in 30 Giorni Di JavaScript
24. Usare il metodo __concat()__ e unire '30 giorni di' e 'JavaScript' in un'unica stringa, '30 giorni di JavaScript'.
25. Usate il metodo __repeat()__ per stampare 30 Giorni Di JavaScript 2 volte.
### Esercizio: Livello 2
1. Utilizzando console.log() stampate la seguente dichiarazione:
```sh
The quote 'There is no exercise better for the heart than reaching down and lifting people up.' by John Holmes teaches us to help one another.
```
2. Utilizzando console.log() stampate la seguente citazione di Madre Teresa:
```sh
"Love is not patronizing and charity isn't about pity, it is about love. Charity and love are the same -- with charity you give love, so don't just give money but reach out your hand instead."
```
3. Verificare se typeof '10' è esattamente uguale a 10. Se non lo è, renderlo esattamente uguale.
4. Verificare se parseFloat('9.8') è uguale a 10. In caso contrario, renderlo esattamente uguale a 10.
5. Controllare se 'on' si trova sia in python che in jargon.
6. Spero che questo corso non sia pieno di jargon. Verificate se _il gergo_ è presente nella frase.
7. Generare un numero casuale compreso tra 0 e 100.
8. Generare un numero casuale compreso tra 50 e 100, incluso.
9. Generare un numero casuale compreso tra 0 e 255 incluso.
10. Accedere ai caratteri della stringa 'JavaScript' utilizzando un numero casuale.
11. Usare console.log() e i caratteri di escape per stampare il seguente schema.
```js
1 1 1 1 1
2 1 2 4 8
3 1 3 9 27
4 1 4 16 64
5 1 5 25 125
```
12. Usa __substr__ per tagliare la frase __perché perché perché perché__ dalla seguente frase:__'Non si può concludere una frase con perché perché perché è una congiunzione'__
### Esercizio: Livello 3
1. L'amore è la cosa migliore di questo mondo. Alcuni hanno trovato il loro amore e altri lo stanno ancora cercando". Contate il numero di parole __amore__ in questa frase.
2. Usate __match()__ per contare il numero di tutti i __perché__ nella seguente frase:__"Non si può concludere una frase con perché perché perché è una congiunzione"__.
3. Pulite il testo seguente e trovate la parola più frequente (suggerimento: usate replace ed espressioni regolari).
```js
const sentence = '%I $am@% a %tea@cher%, &and& I lo%#ve %te@a@ching%;. The@re $is no@th@ing; &as& mo@re rewarding as educa@ting &and& @emp%o@weri@ng peo@ple. ;I found tea@ching m%o@re interesting tha@n any ot#her %jo@bs. %Do@es thi%s mo@tiv#ate yo@u to be a tea@cher!? %Th#is 30#Days&OfJavaScript &is al@so $the $resu@lt of &love& of tea&ching'
```
4. Calcolare il reddito totale annuo della persona estraendo i numeri dal testo seguente. 'Guadagna 5000 euro di stipendio al mese, 10000 euro di bonus annuale, 15000 euro di corsi online al mese'.
🎉 CONGRATULAZIONI ! 🎉
[<< Giorno 1](../readMe.md) | [Giorno 3 >>](../03_Day_Booleans_operators_date/03_booleans_operators_date.md)

@ -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)
![Thirty Days Of JavaScript](../../images/banners/day_1_3.png)
- [📔 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 di Assegnamento](../../images/assignment_operators.png)
### 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.
![Operatori di Confronto](../../images/comparison_operators.png)
**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()_
![Date time Object](../../images/date_time_object.png)
### 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_4.png)
- [📔 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)
![Day 5](../../images/banners/day_1_5.png)
- [📔 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.
![arr index](../../images/array_index.png)
```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)
![Day 5](../../images/banners/day_1_6.png)
- [📔 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,708 @@
<div align="center">
<h1> 30 Days Of JavaScript: Functions</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 6](../06_Day_Loops/06_day_loops.md) | [Day 8 >>](../08_Day_Objects/08_day_objects.md)
![Thirty Days Of JavaScript](../../images/banners/day_1_7.png)
- [📔 Giorno 7](#-day-7)
- [Funzioni](#functions)
- [Dichiarare una Funzione](#function-declaration)
- [Funzione senza parametro e valore di ritorno](#function-without-a-parameter-and-return)
- [Funzione con valore di ritorno](#function-returning-value)
- [Funzione con un parametro](#function-with-a-parameter)
- [Funzione con due parametri](#function-with-two-parameters)
- [Funzione con molti parametri](#function-with-many-parameters)
- [Funzione con numero illimitato di parametri](#function-with-unlimited-number-of-parameters)
- [Numero illimitato di parametri nelle funzioni regolari](#unlimited-number-of-parameters-in-regular-function)
- [Numero illimitato di parametri nelle arrow function](#unlimited-number-of-parameters-in-arrow-function)
- [Anonymous Function](#anonymous-function)
- [Expression Function](#expression-function)
- [Self Invoking Functions](#self-invoking-functions)
- [Arrow Function](#arrow-function)
- [Funzioni con parametri di default](#function-with-default-parameters)
- [Dichiarazione di funzione vs Arrow function](#function-declaration-versus-arrow-function)
- [💻 Esercizi](#-exercises)
- [Esercizi: Livello 1](#exercises-level-1)
- [Esercizi: Livello 2](#exercises-level-2)
- [Esercizi: Livello 3](#exercises-level-3)
# 📔 Giorno 7
## Funzioni
Finora abbiamo visto molte funzioni JavaScript integrate. In questa sezione ci concentreremo sulle funzioni personalizzate. Che cos'è una funzione? Prima di iniziare a creare funzioni, cerchiamo di capire cos'è una funzione e perché ne abbiamo bisogno.
Una funzione è un blocco riutilizzabile di codice o di istruzioni di programmazione progettato per eseguire un determinato compito.
Una funzione è dichiarata da una parola chiave seguita da un nome, seguita da parentesi (). Una parentesi può contenere un parametro. Se una funzione accetta un parametro, verrà chiamata con un argomento. Una funzione può anche accettare un parametro predefinito. Per memorizzare un dato in una funzione, questa deve restituire determinati tipi di dati. Per ottenere il valore si chiama o si invoca una funzione.
Le funzioni rendono il codice
- pulito e facile da leggere
- riutilizzabile
- facile da testare
Una funzione può essere dichiarata o creata in due modi:
- _Declaration function_
- _Expression function_
- _Anonymous function_
- _Arrow function_
### Dichiarare una Funzione
Vediamo come dichiarare una funzione e come chiamare una funzione.
```js
//declaring a function without a parameter
function functionName() {
// code goes here
}
functionName() // calling function by its name and with parentheses
```
### Funzione senza parametro e valore di ritorno
Le funzioni possono essere dichiarate senza parametri.
**Esempio:**
```js
// function without parameter, a function which make a number square
function square() {
let num = 2
let sq = num * num
console.log(sq)
}
square() // 4
// function without parameter
function addTwoNumbers() {
let numOne = 10
let numTwo = 20
let sum = numOne + numTwo
console.log(sum)
}
addTwoNumbers() // a function has to be called by its name to be executed
```
```js
function printFullName (){
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let space = ' '
let fullName = firstName + space + lastName
console.log(fullName)
}
printFullName() // calling a function
```
### Funzione con valore di ritorno
Le funzioni possono anche restituire valori; se una funzione non restituisce valori, il valore della funzione è indefinito. Scriviamo le funzioni di cui sopra con il ritorno. D'ora in poi, restituiremo il valore a una funzione invece di stamparlo.
```js
function printFullName (){
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(printFullName())
```
```js
function addTwoNumbers() {
let numOne = 2
let numTwo = 3
let total = numOne + numTwo
return total
}
console.log(addTwoNumbers())
```
### Funzione con un parametro
In una funzione si possono passare come parametri diversi tipi di dati (numero, stringa, booleano, oggetto, funzione).
```js
// function with one parameter
function functionName(parm1) {
//code goes her
}
functionName(parm1) // during calling or invoking one argument needed
function areaOfCircle(r) {
let area = Math.PI * r * r
return area
}
console.log(areaOfCircle(10)) // should be called with one argument
function square(number) {
return number * number
}
console.log(square(10))
```
### Funzione con due parametri
```js
// function with two parameters
function functionName(parm1, parm2) {
//code goes her
}
functionName(parm1, parm2) // during calling or invoking two arguments needed
// Function without parameter doesn't take input, so lets make a function with parameters
function sumTwoNumbers(numOne, numTwo) {
let sum = numOne + numTwo
console.log(sum)
}
sumTwoNumbers(10, 20) // calling functions
// If a function doesn't return it doesn't store data, so it should return
function sumTwoNumbers(numOne, numTwo) {
let sum = numOne + numTwo
return sum
}
console.log(sumTwoNumbers(10, 20))
function printFullName(firstName, lastName) {
return `${firstName} ${lastName}`
}
console.log(printFullName('Asabeneh', 'Yetayeh'))
```
### Funzione con molti parametri
```js
// function with multiple parameters
function functionName(parm1, parm2, parm3,...){
//code goes here
}
functionName(parm1,parm2,parm3,...) // during calling or invoking three arguments needed
// this function takes array as a parameter and sum up the numbers in the array
function sumArrayValues(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum;
}
const numbers = [1, 2, 3, 4, 5];
//calling a function
console.log(sumArrayValues(numbers));
const areaOfCircle = (radius) => {
let area = Math.PI * radius * radius;
return area;
}
console.log(areaOfCircle(10))
```
### Funzione con numero illimitato di parametri
A volte non sappiamo quanti argomenti l'utente ci passerà. Pertanto, dobbiamo sapere come scrivere una funzione che può accettare un numero illimitato di argomenti. Il modo in cui lo facciamo presenta una differenza significativa tra una dichiarazione di funzione (funzione regolare) e una funzione freccia (arrow function). Vediamo alcuni esempi di dichiarazione di funzione e di funzione freccia.
#### Numero illimitato di parametri nelle funzioni regolari
Una dichiarazione di funzione fornisce un array di argomenti con ambito di funzione come un oggetto. Qualsiasi cosa passata come argomento nella funzione può essere accessibile dall'oggetto argomenti all'interno delle funzioni. Vediamo un esempio
```js
// Let us access the arguments object
function sumAllNums() {
console.log(arguments)
}
sumAllNums(1, 2, 3, 4)
// Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
```
```js
// function declaration
function sumAllNums() {
let sum = 0
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i]
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4)) // 10
console.log(sumAllNums(10, 20, 13, 40, 10)) // 93
console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173
```
#### Numero illimitato di parametri nelle arrow function
La funzione Arrow non ha l'oggetto argomenti con ambito di funzione. Per implementare una funzione che accetta un numero illimitato di argomenti, in una funzione freccia si utilizza l'operatore spread seguito da un qualsiasi nome di parametro. Qualsiasi cosa passata come argomento nella funzione può essere accessibile come array nella funzione freccia. Vediamo un esempio
```js
// Let us access the arguments object
const sumAllNums = (...args) => {
// console.log(arguments), arguments object not found in arrow function
// instead we use a parameter followed by spread operator (...)
console.log(args)
}
sumAllNums(1, 2, 3, 4)
// [1, 2, 3, 4]
```
```js
// function declaration
const sumAllNums = (...args) => {
let sum = 0
for (const element of args) {
sum += element
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4)) // 10
console.log(sumAllNums(10, 20, 13, 40, 10)) // 93
console.log(sumAllNums(15, 20, 30, 25, 10, 33, 40)) // 173
```
### Anonymous Function
Funzione anonima o senza nome
```js
const anonymousFun = function() {
console.log(
'I am an anonymous function and my value is stored in anonymousFun'
)
}
```
### Expression Function
Le Expression Function sono funzioni anonime. Dopo aver creato una funzione senza nome, la assegniamo a una variabile. Per restituire un valore dalla funzione, dobbiamo chiamare la variabile. Guardate l'esempio seguente.
```js
// Function expression
const square = function(n) {
return n * n
}
console.log(square(2)) // -> 4
```
### Self Invoking Functions
Le funzioni Self Invoking sono funzioni anonime che non hanno bisogno di essere chiamate per restituire un valore.
```js
(function(n) {
console.log(n * n)
})(2) // 4, but instead of just printing if we want to return and store the data, we do as shown below
let squaredNum = (function(n) {
return n * n
})(10)
console.log(squaredNum)
```
### Arrow Function
La Arrow function è un'alternativa per scrivere una funzione, tuttavia la dichiarazione di funzione e la Arrow function presentano alcune piccole differenze.
La Arrow function utilizza la freccia invece della parola chiave *function* per dichiarare una funzione. Vediamo la dichiarazione di funzione e la funzione freccia.
```js
// This is how we write normal or declaration function
// Let us change this declaration function to an arrow function
function square(n) {
return n * n
}
console.log(square(2)) // 4
const square = n => {
return n * n
}
console.log(square(2)) // -> 4
// if we have only one line in the code block, it can be written as follows, explicit return
const square = n => n * n // -> 4
```
```js
const changeToUpperCase = arr => {
const newArr = []
for (const element of arr) {
newArr.push(element.toUpperCase())
}
return newArr
}
const countries = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland']
console.log(changeToUpperCase(countries))
// ["FINLAND", "SWEDEN", "NORWAY", "DENMARK", "ICELAND"]
```
```js
const printFullName = (firstName, lastName) => {
return `${firstName} ${lastName}`
}
console.log(printFullName('Asabeneh', 'Yetayeh'))
```
La funzione di cui sopra ha solo l'istruzione return, quindi possiamo restituirla esplicitamente come segue.
```js
const printFullName = (firstName, lastName) => `${firstName} ${lastName}`
console.log(printFullName('Asabeneh', 'Yetayeh'))
```
### Funzioni con parametri di default
A volte si passano dei valori predefiniti ai parametri; quando si invoca la funzione, se non si passa un argomento, verrà utilizzato il valore predefinito. Sia la dichiarazione di funzione che la funzione freccia possono avere uno o più valori predefiniti.
```js
// syntax
// Declaring a function
function functionName(param = value) {
//codes
}
// Calling function
functionName()
functionName(arg)
```
**Esempio:**
```js
function greetings(name = 'Peter') {
let message = `${name}, welcome to 30 Days Of JavaScript!`
return message
}
console.log(greetings())
console.log(greetings('Asabeneh'))
```
```js
function generateFullName(firstName = 'Asabeneh', lastName = 'Yetayeh') {
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(generateFullName())
console.log(generateFullName('David', 'Smith'))
```
```js
function calculateAge(birthYear, currentYear = 2019) {
let age = currentYear - birthYear
return age
}
console.log('Age: ', calculateAge(1819))
```
```js
function weightOfObject(mass, gravity = 9.81) {
let weight = mass * gravity + ' N' // the value has to be changed to string first
return weight
}
console.log('Weight of an object in Newton: ', weightOfObject(100)) // 9.81 gravity at the surface of Earth
console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gravity at surface of Moon
```
Vediamo come scrivere le funzioni di cui sopra con le funzioni a freccia
```js
// syntax
// Declaring a function
const functionName = (param = value) => {
//codes
}
// Calling function
functionName()
functionName(arg)
```
**Esempio:**
```js
const greetings = (name = 'Peter') => {
let message = name + ', welcome to 30 Days Of JavaScript!'
return message
}
console.log(greetings())
console.log(greetings('Asabeneh'))
```
```js
const generateFullName = (firstName = 'Asabeneh', lastName = 'Yetayeh') => {
let space = ' '
let fullName = firstName + space + lastName
return fullName
}
console.log(generateFullName())
console.log(generateFullName('David', 'Smith'))
```
```js
const calculateAge = (birthYear, currentYear = 2019) => currentYear - birthYear
console.log('Age: ', calculateAge(1819))
```
```js
const weightOfObject = (mass, gravity = 9.81) => mass * gravity + ' N'
console.log('Weight of an object in Newton: ', weightOfObject(100)) // 9.81 gravity at the surface of Earth
console.log('Weight of an object in Newton: ', weightOfObject(100, 1.62)) // gravity at surface of Moon
```
### Dichiarazione di funzione vs Arrow function
Verrà trattato in un'altra sezione.
🌕 Sei una stella nascente, ora conosci le funzioni. Sei super carico del potere delle funzioni. Hai appena completato le sfide del 7° giorno e sei a 7 passi dalla strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## 💻 Esercizi
### Esercizi: Livello 1
1. Dichiarare una funzione _fullName_ e stampare il proprio nome completo.
2. Dichiarare una funzione _fullName_ che prenda come parametro firstName e lastName e restituisca il nome completo.
3. Dichiarate una funzione _addNumbers_ che prende due parametri e restituisce la somma.
4. L'area di un rettangolo si calcola come segue: _area = lunghezza x larghezza_. Scrivete una funzione che calcoli l'_area del rettangolo_.
5. Il perimetro di un rettangolo si calcola come segue: _perimetro= 2x(lunghezza + larghezza)_. Scrivete una funzione che calcoli il _perimetro del rettangolo_.
6. Il volume di un prisma rettangolare si calcola come segue: _volume = lunghezza x larghezza x altezza_. Scrivete una funzione che calcoli il _volume del prisma rettangolare_.
7. L'area di un cerchio si calcola come segue: _area = π x r x r_. Scrivere una funzione che calcoli _areaOfCircle_.
8. La circonferenza di un cerchio si calcola come segue: _circonferenza = 2πr_. Scrivere una funzione che calcoli _circonferenza_.
9. La densità di una sostanza si calcola come segue:_densità= massa/volume_. Scrivete una funzione che calcoli la _densità_.
10. La velocità si calcola dividendo la distanza totale coperta da un oggetto in movimento per il tempo totale impiegato. Scrivete una funzione che calcoli la velocità di un oggetto in movimento, _velocità_.
11. Il peso di una sostanza si calcola come segue: _peso = massa x gravità_. Scrivete una funzione che calcoli il _peso_.
12. La temperatura in oC può essere convertita in oF utilizzando questa formula: _oF = (oC x 9/5) + 32_. Scrivete una funzione che converta oC in oF _convertCelsiusToFahrenheit_.
13. L'indice di massa corporea (BMI) si calcola come segue: _bmi = peso in Kg / (altezza x altezza) in m2_. Scrivete una funzione che calcoli il _bmi_. L'IMC viene utilizzato per definire in modo generale diversi gruppi di peso negli adulti di 20 anni o più.Verificate se una persona è _sottopeso, normale, sovrappeso_ o _obesa_ sulla base delle informazioni fornite di seguito.
- Gli stessi gruppi si applicano sia agli uomini che alle donne.
- Sottopeso: L'IMC è inferiore a 18,5
- Peso normale: L'IMC è compreso tra 18,5 e 24,9
- Sovrappeso: IMC compreso tra 25 e 29,9
- _Obesità_: IMC pari o superiore a 30
14. Scrivete una funzione chiamata _checkSeason_, che prende un parametro mese e restituisce la stagione: autunno, inverno, primavera o estate.
15. Math.max restituisce il suo argomento più grande. Scrivete una funzione findMax che prenda tre argomenti e restituisca il loro massimo senza usare il metodo Math.max.
```js
console.log(findMax(0, 10, 5))
10
console.log(findMax(0, -10, -2))
0
```
### Esercizi: Livello 2
1. L'equazione lineare è calcolata come segue: _ax + by + c = 0_. Scrivete una funzione che calcola il valore di un'equazione lineare, _solveLinEquation_.
2. L'equazione quadratica si calcola come segue: _ax2 + bx + c = 0_. Scrivete una funzione che calcoli il valore o i valori di un'equazione quadratica, _solveQuadEquation_.
```js
console.log(solveQuadratic()) // {0}
console.log(solveQuadratic(1, 4, 4)) // {-2}
console.log(solveQuadratic(1, -1, -2)) // {2, -1}
console.log(solveQuadratic(1, 7, 12)) // {-3, -4}
console.log(solveQuadratic(1, 0, -4)) //{2, -2}
console.log(solveQuadratic(1, -1, 0)) //{1, 0}
```
3. Dichiarare una funzione chiamata _printArray_. Prende un array come parametro e stampa ogni valore dell'array.
4. Scrivete una funzione di nome _showDateTime_ che mostra l'ora in questo formato: 08/01/2020 04:08 utilizzando l'oggetto Date.
```sh
showDateTime()
08/01/2020 04:08
```
5. Dichiarare il nome della funzione _swapValues_. Questa funzione scambia il valore di x con quello di y.
```js
swapValues(3, 4) // x => 4, y=>3
swapValues(4, 5) // x = 5, y = 4
```
6. Dichiarare una funzione chiamata _reverseArray_. Prende un array come parametro e restituisce l'inverso dell'array (non usare il metodo).
```js
console.log(reverseArray([1, 2, 3, 4, 5]))
//[5, 4, 3, 2, 1]
console.log(reverseArray(['A', 'B', 'C']))
//['C', 'B', 'A']
```
7. Dichiarare il nome della funzione _capitalizeArray_. Prende l'array come parametro e restituisce l'array - maiuscolo.
8. Dichiarare una funzione di nome _addItem_. Prende come parametro un elemento e restituisce un array dopo l'aggiunta dell'elemento.
9. Dichiarare una funzione di nome _removeItem_. Richiede un parametro indice e restituisce un array dopo la rimozione di un elemento.
10. Dichiarare una funzione di nome _sumOfNumbers_. Richiede un parametro numero e somma tutti i numeri in quell'intervallo.
11. Dichiarare una funzione di nome _sumOfOdds_. Prende come parametro un numero e somma tutti i numeri dispari in quell'intervallo.
12. Dichiarare una funzione di nome _sumOfEven_. Prende come parametro un numero e somma tutti i numeri pari in quell'intervallo.
13. Dichiarare il nome di una funzione _EvensAndOdds_. Prende come parametro un numero intero positivo e conta il numero di pari e dispari nel numero.
```sh
evensAndOdds(100);
The number of odds are 50.
The number of evens are 51.
```
14. Scrivere una funzione che accetta un numero qualsiasi di argomenti e restituisce la somma degli argomenti.
```js
sum(1, 2, 3) // -> 6
sum(1, 2, 3, 4) // -> 10
```
15. Scrivere una funzione che generi un _randomUserIp_.
16. Scrivere una funzione che generi un _randomMacAddress_.
17. Dichiarare il nome di una funzione _randomHexaNumberGenerator_. Quando questa funzione viene chiamata, genera un numero esadecimale casuale. La funzione restituisce il numero esadecimale.
```sh
console.log(randomHexaNumberGenerator());
'#ee33df'
```
18. Dichiarare il nome della funzione _userIdGenerator_. Quando questa funzione viene chiamata, genera un id di sette caratteri. La funzione restituisce l'id.
```sh
console.log(userIdGenerator());
41XTDbE
```
### Esercizi: Livello 3
1. Modificare la funzione _userIdGenerator_. Dichiarare il nome della funzione _userIdGeneratedByUser_. Non accetta alcun parametro, ma prende due input tramite prompt(). Uno di questi è il numero di caratteri e il secondo è il numero di ID che devono essere generati.
```sh
userIdGeneratedByUser()
'kcsy2
SMFYb
bWmeq
ZXOYh
2Rgxf
'
userIdGeneratedByUser()
'1GCSgPLMaBAVQZ26
YD7eFwNQKNs7qXaT
ycArC5yrRupyG00S
UbGxOFI7UXSWAyKN
dIV0SSUTgAdKwStr
'
```
2. Scrivete una funzione chiamata _rgbColorGenerator_ che genera i colori rgb.
```sh
rgbColorGenerator()
rgb(125,244,255)
```
3. Scrivere una funzione **_arrayOfHexaColors_** che restituisca un numero qualsiasi di colori esadecimali in un array.
4. Scrivete una funzione **_arrayOfRgbColors_** che restituisca un numero qualsiasi di colori RGB in una matrice.
5. Scrivere una funzione **_convertHexaToRgb_** che converta il colore hexa in rgb e restituisca un colore rgb.
6. Scrivere una funzione **_convertRgbToHexa_** che converta il colore rgb in hexa e restituisca un colore hexa.
7. Scrivere una funzione **_generateColors_** che possa generare un numero qualsiasi di colori hexa o rgb.
```js
console.log(generateColors('hexa', 3)) // ['#a3e12f', '#03ed55', '#eb3d2b']
console.log(generateColors('hexa', 1)) // '#b334ef'
console.log(generateColors('rgb', 3)) // ['rgb(5, 55, 175)', 'rgb(50, 105, 100)', 'rgb(15, 26, 80)']
console.log(generateColors('rgb', 1)) // 'rgb(33,79, 176)'
```
8. Chiamare la funzione _shuffleArray_, che prende un array come parametro e restituisce un array mescolato.
9. Chiamate la vostra funzione _factorial_, che prende un numero intero come parametro e restituisce un fattoriale del numero
10. Chiamate la funzione _isEmpty_, che prende un parametro e controlla se è vuoto o meno.
11. Chiamate la funzione _sum_, che accetta un numero qualsiasi di argomenti e restituisce la somma.
12. Scrivete una funzione chiamata _sumOfArrayItems_, che accetta un parametro dell'array e restituisce la somma di tutti gli elementi. Verificare se tutti gli elementi dell'array sono di tipo numero. In caso contrario, restituire un feedback ragionevole.
13. Scrivete una funzione chiamata _media_, che accetta un parametro di array e restituisce la media degli elementi. Verificate se tutti gli elementi dell'array sono di tipo numero. In caso contrario, restituire un feedback ragionevole.
14. Scrivere una funzione chiamata _modifyArray_ che prenda come parametro un array e modifichi il quinto elemento dell'array e restituisca l'array. Se la lunghezza dell'array è inferiore a cinque, restituisce "elemento non trovato".
```js
console.log(modifyArray(['Avocado', 'Tomato', 'Potato','Mango', 'Lemon','Carrot']);
```
```sh
['Avocado', 'Tomato', 'Potato','Mango', 'LEMON', 'Carrot']
```
```js
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon','Microsoft', 'IBM']);
```
```sh
['Google', 'Facebook','Apple', 'Amazon','MICROSOFT', 'IBM']
```
```js
console.log(modifyArray(['Google', 'Facebook','Apple', 'Amazon']);
```
```sh
'Not Found'
```
15. Scrivere una funzione chiamata _isPrime_, che verifichi se un numero è un numero primo.
16. Scrivete una funzione che verifichi se tutti gli elementi sono unici nell'array.
17. Scrivete una funzione che verifichi se tutti gli elementi dell'array sono dello stesso tipo di dati.
18. Il nome della variabile JavaScript non supporta caratteri speciali o simboli, tranne \$ o \_. Scrivete una funzione **isValidVariable** che controlli se una variabile è valida o non valida.
19. Scrivete una funzione che restituisca un array di sette numeri casuali in un intervallo compreso tra 0 e 9. Tutti i numeri devono essere unici. Tutti i numeri devono essere unici.
```js
sevenRandomNumbers()
[(1, 4, 5, 7, 9, 8, 0)]
```
20. Scrivere una funzione chiamata reverseCountries, che prenda un array di paesi e prima copi l'array e restituisca l'inverso dell'array originale.
🎉 CONGRATULAZIONI ! 🎉
[<< Day 6](../06_Day_Loops/06_day_loops.md) | [Day 8 >>](../08_Day_Objects/08_day_objects.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)
![Thirty Days Of JavaScript](../../images/banners/day_1_8.png)
- [📔 Giorno 8](#-day-8)
- [Scope](#scope)
- [Window Global Object](#window-global-object)
- [Global scope](#global-scope)
- [Local scope](#local-scope)
- [📔 Object](#-object)
- [Creare un oggetto vuoto](#creating-an-empty-object)
- [Creare un oggetto con valori](#creating-an-objecting-with-values)
- [Ottenere i valori dall'oggetto](#getting-values-from-an-object)
- [Creare i metodi di un oggetto](#creating-object-methods)
- [Impostare nuove chiavi per un oggetto](#setting-new-key-for-an-object)
- [Metodi della classe Object](#object-methods)
- [Ottenere le chiavi con Object.keys()](#getting-object-keys-using-objectkeys)
- [Ottenere i valori con Object.values()](#getting-object-values-using-objectvalues)
- [Ottenere chiavi e valori con Object.entries()](#getting-object-keys-and-values-using-objectentries)
- [Controllare le proprietà usando 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
La variabile è un elemento fondamentale della programmazione. Dichiariamo una variabile per memorizzare diversi tipi di dati. Per dichiarare una variabile si usano le parole chiave _var_, _let_ e _const_. Una variabile può essere dichiarata in diversi ambiti. In questa sezione vedremo l'ambito delle variabili, l'ambito delle variabili quando usiamo var o let.
Gli ambiti delle variabili possono essere:
- Global
- Local
Le variabili possono essere dichiarate a livello globale o locale. Vedremo sia l'ambito globale che quello locale.
Qualsiasi cosa dichiarata senza let, var o const ha uno scope globale.
Immaginiamo di avere un file scope.js.
### Window Global Object
Senza usare console.log(), aprite il browser e verificate: vedrete il valore di a e b se scrivete a o b nel browser. Ciò significa che a e b sono già disponibili nella finestra.
```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
Una variabile dichiarata globalmente può essere accessibile in qualsiasi punto dello stesso file. Ma il termine globale è relativo. Può essere globale al file o globale rispetto a qualche blocco di codice.
```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
Una variabile dichiarata come locale può essere accessibile solo in determinati blocchi di codice.
- 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
```
Ora avete compreso l'ambito. Una variabile dichiarata con *var* ha un ambito solo per la funzione, mentre una variabile dichiarata con *let* o *const* ha un ambito di blocco (blocco funzione, blocco if, blocco loop, ecc.). Il blocco in JavaScript è un codice compreso tra due parentesi graffe ({}).
```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 e versioni successive esistono *let* e *const*, per cui non si soffrirà della subdola presenza di *var*. Quando usiamo *let*, la nostra variabile ha uno scope di blocco e non infetterà altre parti del nostro codice.
```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
```
Gli ambiti *let* e *const* sono gli stessi. La differenza è solo la riassegnazione. Non possiamo cambiare o riassegnare il valore della variabile `const`. Vi consiglio vivamente di usare *let* e *const*; usando *let* e *const* scriverete codice pulito ed eviterete errori difficili da debuggare. Come regola generale, si può usare *let* per qualsiasi valore che cambia, *const* per qualsiasi valore costante e per un array, un oggetto, una funzione freccia e un'espressione di funzione.
## 📔 Object
Tutto può essere un oggetto e gli oggetti hanno proprietà e le proprietà hanno valori, quindi un oggetto è una coppia chiave-valore. L'ordine delle chiavi non è riservato, oppure non c'è un ordine.
Per creare un letterale di oggetto, si usano due parentesi graffe.
### Creare un oggetto vuoto
An empty object
```js
const person = {}
```
### Creare un oggetto con valori
Ora, l'oggetto persona ha le proprietà firstName, lastName, age, location, skills e isMarried. Il valore delle proprietà o delle chiavi può essere una stringa, un numero, un booleano, un oggetto, null, undefined o una funzione.
Vediamo alcuni esempi di oggetti. Ogni chiave ha un valore nell'oggetto.
```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)
```
### Ottenere i valori dall'oggetto
Possiamo accedere ai valori degli oggetti utilizzando due metodi:
- usando . seguito dal nome della chiave, se il nome della chiave è una sola parola
- usando le parentesi quadre e le virgolette
```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'])
```
### Creare i metodi di un oggetto
Ora, l'oggetto persona ha le proprietà getFullName. Il metodo getFullName è una funzione all'interno dell'oggetto persona e lo chiamiamo metodo dell'oggetto. La parola chiave _this_ si riferisce all'oggetto stesso. Possiamo usare la parola _this_ per accedere ai valori di diverse proprietà dell'oggetto. Non possiamo usare una funzione freccia come metodo oggetto, perché la parola this si riferisce alla finestra all'interno di una funzione freccia invece che all'oggetto stesso. Esempio di oggetto:
```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
```
### Impostare nuove chiavi per un oggetto
Un oggetto è una struttura dati mutabile e si può modificare il contenuto di un oggetto dopo la sua creazione.
Impostazione di nuove chiavi in un oggetto
```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.
```
### Metodi della classe Object
Esistono diversi metodi per manipolare un oggetto. Vediamo alcuni dei metodi disponibili.
_Object.assign_: Per copiare un oggetto senza modificare l'oggetto originale.
```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)
```
#### Ottenere le chiavi con Object.keys()
_Object.keys_: Per ottenere le chiavi o le proprietà di un oggetto come 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']
```
#### Ottenere i valori con Object.values()
_Object.values_:Per ottenere i valori di un oggetto come array
```js
const values = Object.values(copyPerson)
console.log(values)
```
#### Ottenere chiavi e valori con Object.entries()
_Object.entries_: Per ottenere le chiavi e i valori di un array
```js
const entries = Object.entries(copyPerson)
console.log(entries)
```
#### Controllare le proprietà usando hasOwnProperty()
_hasOwnProperty_: Per verificare se una chiave o una proprietà specifica esiste in un oggetto
```js
console.log(copyPerson.hasOwnProperty('name'))
console.log(copyPerson.hasOwnProperty('score'))
```
🌕 Sei sorprendente. Ora sei super caricato con il potere degli oggetti. Hai appena completato le sfide dell'ottavo giorno e sei a 8 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## 💻 Esercizi
### Esercizi: Livello 1
1. Creare un oggetto vuoto chiamato cane
1. Stampare l'oggetto cane sulla console
1. Aggiungere all'oggetto cane le proprietà nome, zampe, colore, età e abbaio. La proprietà abbaia è un metodo che restituisce _woof woof_.
1. Ottenere il valore di nome, zampe, colore, età e abbaio dall'oggetto cane
1. Impostare nuove proprietà per l'oggetto cane: breed, getDogInfo
### Esercizi: Livello 2
1. Individuare la persona che ha molte competenze nell'oggetto utente.
1. Contare gli utenti connessi, contare gli utenti che hanno più di 50 punti dal seguente oggetto.
````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. Trovare persone che sono sviluppatori di stack MERN dall'oggetto degli utenti
1. Impostare il proprio nome nell'oggetto utenti senza modificare l'oggetto utenti originale.
1. Ottenere tutte le chiavi o le proprietà dell'oggetto users
1. Ottenere tutti i valori dell'oggetto users
1. Utilizzare l'oggetto countries per stampare il nome di un paese, la capitale, la popolazione e le lingue.
### Esercizi: Livello 3
1. Creare un oggetto letterale chiamato _contopersona_. Ha le proprietà _nome, cognome, entrate, spese_ e i metodi _entrate totali, uscite totali, informazioni sul conto, aggiungi entrate, aggiungi spese_ e _bilancio del conto_. Entrate è un insieme di entrate e relativa descrizione e spese è un insieme di entrate e relativa descrizione.
2. **** Le domande:2, 3 e 4 si basano sui seguenti due array: utenti e prodotti ()
```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']
}
]
```
Si immagini di ottenere la raccolta di utenti di cui sopra da un database MongoDB.
a. Creare una funzione chiamata signUp che consenta all'utente di aggiungersi all'insieme. Se l'utente esiste, informarlo che ha già un account.
b. Creare una funzione chiamata signIn che consenta all'utente di accedere all'applicazione.
3. L'array prodotti ha tre elementi e ognuno di essi ha sei proprietà.
a. Creare una funzione chiamata rateProduct che valuta il prodotto.
b. Creare una funzione chiamata mediaValutazione che calcola la media delle valutazioni di un prodotto.
4. Creare una funzione chiamata likeProduct. Questa funzione aiuta a dare un like al prodotto se non è piaciuto e a rimuovere il like se è piaciuto.
🎉 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,705 @@
<div align="center">
<h1> 30 Days Of JavaScript: Higher Order Functions</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 8](../08_Day_Objects/08_day_objects.md) | [Day 10 >>](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md)
![Day 5](../../images/banners/day_1_9.png)
- [Day 9](#day-9)
- [Higher Order Function](#higher-order-function)
- [Callback](#callback)
- [restituire una funzione](#returning-function)
- [Impostare il tempo](#setting-time)
- [Impostare un intervallo con la funzione setInterval](#setting-interval-using-a-setinterval-function)
- [Impostare il tempo di esecuzione di una callback con setTimeout](#setting-a-time-using-a-settimeout)
- [Functional Programming](#functional-programming)
- [forEach](#foreach)
- [map](#map)
- [filter](#filter)
- [reduce](#reduce)
- [every](#every)
- [find](#find)
- [findIndex](#findindex)
- [some](#some)
- [sort](#sort)
- [Ordinare i valori string](#sorting-string-values)
- [Ordinare i valori numbers](#sorting-numeric-values)
- [Ordinare i valori Object](#sorting-object-arrays)
- [💻 Esercizi](#-exercises)
- [Esercizi: Livello 1](#exercises-level-1)
- [Esercizi: Livello 2](#exercises-level-2)
- [Esercizi: Livello 3](#exercises-level-3)
# Day 9
## Higher Order Function
Le funzioni di ordine superiore sono funzioni che accettano un'altra funzione come parametro o restituiscono una funzione come valore. La funzione passata come parametro è chiamata callback.
### Callback
Un callback è una funzione che può essere passata come parametro ad altre funzioni. Si veda l'esempio seguente.
```js
// a callback function, the name of the function could be any name
const callback = (n) => {
return n ** 2
}
// function that takes other function as a callback
function cube(callback, n) {
return callback(n) * n
}
console.log(cube(callback, 3))
```
### restituire una funzione
Le funzioni di ordine superiore restituiscono la funzione come valore
```js
// Higher order function returning an other function
const higherOrder = n => {
const doSomething = m => {
const doWhatEver = t => {
return 2 * n + 3 * m + t
}
return doWhatEver
}
return doSomething
}
console.log(higherOrder(2)(3)(10))
```
Vediamo come utilizzare le funzioni di richiamo. Ad esempio, il metodo _forEach_ utilizza il richiamo.
```js
const numbers = [1, 2, 3, 4, 5]
const sumArray = arr => {
let sum = 0
const callback = function(element) {
sum += element
}
arr.forEach(callback)
return sum
}
console.log(sumArray(numbers))
```
```sh
15
```
L'esempio precedente può essere semplificato come segue:
```js
const numbers = [1, 2, 3, 4]
const sumArray = arr => {
let sum = 0
arr.forEach(function(element) {
sum += element
})
return sum
}
console.log(sumArray(numbers))
```
```sh
15
```
### Impostare il tempo
In JavaScript possiamo eseguire alcune attività in un certo intervallo di tempo oppure possiamo programmare (attendere) l'esecuzione di alcune attività.
- setInterval
- setTimeout
#### Impostare un intervallo con la funzione setInterval
In JavaScript, si usa la funzione di ordine superiore setInterval per eseguire un'attività in modo continuo in un certo intervallo di tempo. Il metodo globale setInterval accetta una funzione di callback e una durata come parametro. La durata è espressa in millisecondi e il callback sarà sempre richiamato in quell'intervallo di tempo.
```js
// syntax
function callback() {
// code goes here
}
setInterval(callback, duration)
```
```js
function sayHello() {
console.log('Hello')
}
setInterval(sayHello, 1000) // it prints hello in every second, 1000ms is 1s
```
#### Impostare il tempo di esecuzione di una callback con setTimeout
In JavaScript, si usa la funzione di ordine superiore setTimeout per eseguire un'azione in un momento futuro. Il metodo globale setTimeout accetta una funzione di callback e una durata come parametro. La durata è espressa in millisecondi e il callback attende per questo lasso di tempo.
```js
// syntax
function callback() {
// code goes here
}
setTimeout(callback, duration) // duration in milliseconds
```
```js
function sayHello() {
console.log('Hello')
}
setTimeout(sayHello, 2000) // it prints hello after it waits for 2 seconds.
```
## Functional Programming
Invece di scrivere cicli regolari, l'ultima versione di JavaScript ha introdotto molti metodi integrati che possono aiutarci a risolvere problemi complicati. Tutti i metodi incorporati richiedono una funzione di callback. In questa sezione vedremo _forEach_, _map_, _filter_, _reduce_, _find_, _every_, _some_ e _sort_.
### forEach
_forEach_: Itera gli elementi di un array. Si usa _forEach_ solo con gli array. Richiede una funzione di callback con elementi, un parametro indice e l'array stesso. L'indice e l'array sono facoltativi.
```js
arr.forEach(function (element, index, arr) {
console.log(index, element, arr)
})
// The above code can be written using arrow function
arr.forEach((element, index, arr) => {
console.log(index, element, arr)
})
// The above code can be written using arrow function and explicit return
arr.forEach((element, index, arr) => console.log(index, element, arr))
```
```js
let sum = 0;
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num))
console.log(sum)
```
```sh
1
2
3
4
5
```
```js
let sum = 0;
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => sum += num)
console.log(sum)
```
```sh
15
```
```js
const countries = ['Finland', 'Denmark', 'Sweden', 'Norway', 'Iceland']
countries.forEach((element) => console.log(element.toUpperCase()))
```
```sh
FINLAND
DENMARK
SWEDEN
NORWAY
ICELAND
```
### map
_map_: Itera gli elementi di un array e modifica gli elementi dell'array. Prende una funzione di callback con elementi, indice, parametro dell'array e restituisce un nuovo array.
```js
const modifiedArray = arr.map(function (element, index, arr) {
return element
})
```
```js
/*Arrow function and explicit return
const modifiedArray = arr.map((element,index) => element);
*/
//Example
const numbers = [1, 2, 3, 4, 5]
const numbersSquare = numbers.map((num) => num * num)
console.log(numbersSquare)
```
```sh
[1, 4, 9, 16, 25]
```
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const namesToUpperCase = names.map((name) => name.toUpperCase())
console.log(namesToUpperCase)
```
```sh
['ASABENEH', 'MATHIAS', 'ELIAS', 'BROOK']
```
```js
const countries = [
'Albania',
'Bolivia',
'Canada',
'Denmark',
'Ethiopia',
'Finland',
'Germany',
'Hungary',
'Ireland',
'Japan',
'Kenya',
]
const countriesToUpperCase = countries.map((country) => country.toUpperCase())
console.log(countriesToUpperCase)
/*
// Arrow function
const countriesToUpperCase = countries.map((country) => {
return country.toUpperCase();
})
//Explicit return arrow function
const countriesToUpperCase = countries.map(country => country.toUpperCase());
*/
```
```sh
['ALBANIA', 'BOLIVIA', 'CANADA', 'DENMARK', 'ETHIOPIA', 'FINLAND', 'GERMANY', 'HUNGARY', 'IRELAND', 'JAPAN', 'KENYA']
```
```js
const countriesFirstThreeLetters = countries.map((country) =>
country.toUpperCase().slice(0, 3)
)
```
```sh
 ["ALB", "BOL", "CAN", "DEN", "ETH", "FIN", "GER", "HUN", "IRE", "JAP", "KEN"]
```
### filter
_Filter_: Filtra gli elementi che soddisfano le condizioni di filtraggio e restituisce un nuovo array.
```js
//Filter countries containing land
const countriesContainingLand = countries.filter((country) =>
country.includes('land')
)
console.log(countriesContainingLand)
```
```sh
['Finland', 'Ireland']
```
```js
const countriesEndsByia = countries.filter((country) => country.endsWith('ia'))
console.log(countriesEndsByia)
```
```sh
['Albania', 'Bolivia','Ethiopia']
```
```js
const countriesHaveFiveLetters = countries.filter(
(country) => country.length === 5
)
console.log(countriesHaveFiveLetters)
```
```sh
['Japan', 'Kenya']
```
```js
const scores = [
{ name: 'Asabeneh', score: 95 },
{ name: 'Lidiya', score: 98 },
{ name: 'Mathias', score: 80 },
{ name: 'Elias', score: 50 },
{ name: 'Martha', score: 85 },
{ name: 'John', score: 100 },
]
const scoresGreaterEighty = scores.filter((score) => score.score > 80)
console.log(scoresGreaterEighty)
```
```sh
[{name: 'Asabeneh', score: 95}, { name: 'Lidiya', score: 98 },{name: 'Martha', score: 85},{name: 'John', score: 100}]
```
### reduce
_reduce_: Reduce accetta una funzione di richiamo. La funzione di richiamo prende come parametro l'accumulatore, il valore corrente e il valore iniziale opzionale e restituisce un singolo valore. È buona norma definire un valore iniziale per il valore dell'accumulatore. Se non si specifica questo parametro, per impostazione predefinita l'accumulatore otterrà il "primo valore" dell'array. Se la nostra matrice è una matrice _vuota_, allora `Javascript` lancerà un errore.
```js
arr.reduce((acc, cur) => {
// some operations goes here before returning a value
return
}, initialValue)
```
```js
const numbers = [1, 2, 3, 4, 5]
const sum = numbers.reduce((acc, cur) => acc + cur, 0)
console.log(sum)
```
```js
15
```
### every
_every_: Controlla se tutti gli elementi sono simili in un aspetto. Restituisce un booleano
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const areAllStr = names.every((name) => typeof name === 'string') // Are all strings?
console.log(areAllStr)
```
```sh
true
```
```js
const bools = [true, true, true, true]
const areAllTrue = bools.every((b) => b === true) // Are all true?
console.log(areAllTrue) // true
```
```sh
true
```
### find
_find_: Restituisce il primo elemento che soddisfa la condizione
```js
const ages = [24, 22, 25, 32, 35, 18]
const age = ages.find((age) => age < 20)
console.log(age)
```
```js
18
```
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const result = names.find((name) => name.length > 7)
console.log(result)
```
```sh
Asabeneh
```
```js
const scores = [
{ name: 'Asabeneh', score: 95 },
{ name: 'Mathias', score: 80 },
{ name: 'Elias', score: 50 },
{ name: 'Martha', score: 85 },
{ name: 'John', score: 100 },
]
const score = scores.find((user) => user.score > 80)
console.log(score)
```
```sh
{ name: "Asabeneh", score: 95 }
```
### findIndex
_findIndex_: Restituisce la posizione del primo elemento che soddisfa la condizione
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const ages = [24, 22, 25, 32, 35, 18]
const result = names.findIndex((name) => name.length > 7)
console.log(result) // 0
const age = ages.findIndex((age) => age < 20)
console.log(age) // 5
```
### some
_some_: Controlla se alcuni elementi sono simili in un aspetto. Restituisce un booleano
```js
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const bools = [true, true, true, true]
const areSomeTrue = bools.some((b) => b === true)
console.log(areSomeTrue) //true
```
```js
const areAllStr = names.some((name) => typeof name === 'number') // Are all strings ?
console.log(areAllStr) // false
```
### sort
_sort_: I metodi di ordinamento dispongono gli elementi dell'array in ordine crescente o decrescente. Per impostazione predefinita, il metodo **_sort()_** ordina i valori come stringhe, il che funziona bene per gli elementi dell'array di stringhe, ma non per i numeri. Se i valori numerici vengono ordinati come stringhe, il risultato è sbagliato. Il metodo Sort modifica l'array originale. Si consiglia di copiare i dati originali prima di iniziare a usare il metodo _sort_.
#### Ordinare i valori string
```js
const products = ['Milk', 'Coffee', 'Sugar', 'Honey', 'Apple', 'Carrot']
console.log(products.sort()) // ['Apple', 'Carrot', 'Coffee', 'Honey', 'Milk', 'Sugar']
//Now the original products array is also sorted
```
#### Ordinare i valori numbers
Come si può vedere nell'esempio seguente, 100 è arrivato per primo dopo l'ordinamento in ordine crescente. L'ordinamento converte gli elementi in stringhe, poiché '100' e altri numeri sono stati confrontati, 1 che all'inizio della stringa '100' è diventato il più piccolo. Per evitare ciò, utilizziamo una funzione di richiamo di confronto all'interno del metodo sort, che restituisce un valore negativo, zero o positivo.
```js
const numbers = [9.81, 3.14, 100, 37]
// Using sort method to sort number items provide a wrong result. see below
console.log(numbers.sort()) //[100, 3.14, 37, 9.81]
numbers.sort(function (a, b) {
return a - b
})
console.log(numbers) // [3.14, 9.81, 37, 100]
numbers.sort(function (a, b) {
return b - a
})
console.log(numbers) //[100, 37, 9.81, 3.14]
```
#### Ordinare i valori Object
Quando si ordinano gli oggetti in una matrice, si utilizza la chiave dell'oggetto da confrontare. Vediamo l'esempio seguente.
```js
objArr.sort(function (a, b) {
if (a.key < b.key) return -1
if (a.key > b.key) return 1
return 0
})
// or
objArr.sort(function (a, b) {
if (a['key'] < b['key']) return -1
if (a['key'] > b['key']) return 1
return 0
})
const users = [
{ name: 'Asabeneh', age: 150 },
{ name: 'Brook', age: 50 },
{ name: 'Eyob', age: 100 },
{ name: 'Elias', age: 22 },
]
users.sort((a, b) => {
if (a.age < b.age) return -1
if (a.age > b.age) return 1
return 0
})
console.log(users) // sorted ascending
// [{…}, {…}, {…}, {…}]
```
🌕Stai andando alla grande. Non arrenderti mai perché le grandi cose richiedono tempo. Hai appena completato le sfide del nono giorno e sei a 9 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## 💻 Esercizi
### Esercizi: Livello 1
```js
const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'IceLand']
const names = ['Asabeneh', 'Mathias', 'Elias', 'Brook']
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const products = [
{ product: 'banana', price: 3 },
{ product: 'mango', price: 6 },
{ product: 'potato', price: ' ' },
{ product: 'avocado', price: 8 },
{ product: 'coffee', price: 10 },
{ product: 'tea', price: '' },
]
```
1. Spiegare la differenza tra **_forEach, map, filter e reduce_**.
2. Definire una funzione di callback prima di utilizzarla in forEach, map, filter o reduce.
3. Usate **_forEach_** per registrare in console.log ogni paese nell'array dei paesi.
4. Usare **_forEach_** per registrare in console.log ogni nome nell'array dei nomi.
5. Usare **_forEach_** per registrare in console.log ogni numero nell'array numbers.
6. Usare **_map_** per creare un nuovo array cambiando ogni paese in maiuscolo nell'array paesi.
7. Usare **_map_** per creare un array di paesi di lunghezza pari a quella dell'array paesi.
8. Usare **_map_** per creare un nuovo array cambiando ogni numero in quadrato nell'array dei numeri.
9. Usare **_map_** per cambiare ogni nome in maiuscolo nell'array dei nomi.
10. Usare **_map_** per mappare l'array dei prodotti ai prezzi corrispondenti.
11. Utilizzare **_filtro_** per filtrare i paesi contenenti **_terra_**.
12. Usare **_filtro_** per filtrare i paesi con sei caratteri.
13. Usare **_filtro_** per filtrare i paesi contenenti sei lettere o più nell'array dei paesi.
14. Usare **_filter_** per filtrare i paesi che iniziano con 'E';
15. Usare **_filter_** per filtrare solo i prezzi con valori.
16. Dichiarare una funzione chiamata getStringLists che accetta un array come parametro e restituisce un array contenente solo elementi stringa.
17. Usare **_reduce_** per sommare tutti i numeri nell'array numbers.
18. Usare **_reduce_** per concatenare tutti i paesi e produrre questa frase: **_Estonia, Finlandia, Svezia, Danimarca, Norvegia e IceLand sono paesi del Nord Europa_**.
19. Spiegate la differenza tra **alcuni_** e **tutti_**.
20. Usate **_qualche_** per verificare se la lunghezza di alcuni nomi è maggiore di sette nell'array dei nomi.
21. Usare **_every_** per verificare se tutti i paesi contengono la parola land (terra).
22. Spiegate la differenza tra **_find_** e **_findIndex_**.
23. Usate **_find_** per trovare il primo paese che contiene solo sei lettere nell'array dei paesi.
24. Usare **_findIndex_** per trovare la posizione del primo paese contenente solo sei lettere nell'array dei paesi.
25. Usare **_findIndex_** per trovare la posizione di **_Norvegia_** se non esiste nell'array si otterrà -1.
26. Usare **_findIndex_** per trovare la posizione di **_Russia_** se non esiste nell'array si otterrà -1.
### Esercizi: Livello 2
1. Trovare il prezzo totale dei prodotti concatenando due o più iteratori di array (es. arr.map(callback).filter(callback).reduce(callback))
1. Trovare la somma dei prezzi dei prodotti usando solo reduce(callback))
1. Dichiarare una funzione chiamata **_categorizeCountries_** che restituisce un array di Paesi che hanno un modello comune (l'array dei Paesi si trova in questo repository come countries.js (ad esempio 'land', 'ia', 'island', 'stan')).
1. Creare una funzione che restituisca un array di oggetti, ovvero la lettera e il numero di volte in cui la lettera inizia con il nome di un paese.
1. Dichiarare una funzione **_getFirstTenCountries_** e restituire un array di dieci paesi. Utilizzare una programmazione funzionale diversa per lavorare sull'array countries.js
1. Dichiarare una funzione **_getLastTenCountries_** che restituisca gli ultimi dieci paesi dell'array countries.
1. Scoprite quale _lettera_ viene usata molte _volte_ come iniziale del nome di un paese dall'array dei paesi (es. Finlandia, Figi, Francia ecc.).
### Esercizi: Livello 3
1. Utilizzate le informazioni sui Paesi, contenute nella cartella dei dati. Ordinare i Paesi per nome, per capitale, per popolazione
1. \*\*\* Trovare le 10 lingue più parlate:
````js
// Your output should look like this
console.log(mostSpokenLanguages(countries, 10))
[
{country: 'English',count:91},
{country: 'French',count:45},
{country: 'Arabic',count:25},
{country: 'Spanish',count:24},
{country:'Russian',count:9},
{country:'Portuguese', count:9},
{country:'Dutch',count:8},
{country:'German',count:7},
{country:'Chinese',count:5},
{country:'Swahili',count:4}
]
// Your output should look like this
console.log(mostSpokenLanguages(countries, 3))
[
{country: 'English',count: 91},
{country: 'French',count: 45},
{country: 'Arabic',count: 25},
]```
````
2. \*\*\* Usare il file countries_data.js per creare una funzione che crei i dieci paesi più popolosi.
````js
console.log(mostPopulatedCountries(countries, 10))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000},
{country: 'Indonesia', population: 258705000},
{country: 'Brazil', population: 206135893},
{country: 'Pakistan', population: 194125062},
{country: 'Nigeria', population: 186988000},
{country: 'Bangladesh', population: 161006790},
{country: 'Russian Federation', population: 146599183},
{country: 'Japan', population: 126960000}
]
console.log(mostPopulatedCountries(countries, 3))
[
{country: 'China', population: 1377422166},
{country: 'India', population: 1295210000},
{country: 'United States of America', population: 323947000}
]
```
````
3. \*\*\* Cercate di sviluppare un programma che calcoli la misura della tendenza centrale di un campione (media, mediana, modalità) e la misura della variabilità (intervallo, varianza, deviazione standard). Oltre a queste misure, trovate il minimo, il massimo, il numero, il percentile e la distribuzione di frequenza del campione. È possibile creare un oggetto chiamato statistiche e creare tutte le funzioni che eseguono calcoli statistici come metodi per l'oggetto statistiche. Verificate l'output qui sotto.
```js
const ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
console.log('Count:', statistics.count()) // 25
console.log('Sum: ', statistics.sum()) // 744
console.log('Min: ', statistics.min()) // 24
console.log('Max: ', statistics.max()) // 38
console.log('Range: ', statistics.range() // 14
console.log('Mean: ', statistics.mean()) // 30
console.log('Median: ',statistics.median()) // 29
console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5}
console.log('Variance: ',statistics.var()) // 17.5
console.log('Standard Deviation: ', statistics.std()) // 4.2
console.log('Variance: ',statistics.var()) // 17.5
console.log('Frequency Distribution: ',statistics.freqDist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
```sh
console.log(statistics.describe())
Count: 25
Sum: 744
Min: 24
Max: 38
Range: 14
Mean: 30
Median: 29
Mode: (26, 5)
Variance: 17.5
Standard Deviation: 4.2
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
🎉 CONGRATULAZIONI ! 🎉
[<< Day 8](../08_Day_Objects/08_day_objects.md) | [Day 10 >>](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md)

@ -0,0 +1,440 @@
<div align="center">
<h1> 30 Days Of JavaScript: Sets and Maps</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 9](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) | [Day 11>>](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md)
![Day 10](../../images/banners/day_1_10.png)
- [Day 10](#day-10)
- [Set](#set)
- [Creare un set vuoto](#creating-an-empty-set)
- [Creare un set da un array](#creating-set-from-array)
- [Aggiungere un elemento ad un set](#adding-an-element-to-a-set)
- [Eliminare un elemento dal set](#deleting-an-element-a-set)
- [Verificare la presenza di un elemento nel set](#checking-an-element-in-the-set)
- [Svuotare il set](#clearing-the-set)
- [Unione di set](#union-of-sets)
- [Intersezione di set](#intersection-of-sets)
- [Differenza tra set](#difference-of-sets)
- [Map](#map)
- [Creare un map vuoto](#creating-an-empty-map)
- [Creare un map da un array](#creating-an-map-from-array)
- [Aggiungere valori ad un map](#adding-values-to-the-map)
- [Ottenere un valore dal map](#getting-a-value-from-map)
- [Controllare le key del map](#checking-key-in-map)
- [Esercizi](#exercises)
- [Esercizi: Livello 1](#exerciseslevel-1)
- [Esercizi: Livello 2](#exerciseslevel-2)
- [Esercizi: Livello 3](#exerciseslevel-3)
# Day 10
## Set
L'insieme è una collezione di elementi. L'insieme può contenere solo elementi unici.
Vediamo come creare un insieme nella sezione seguente.
### Creare un set vuoto
```js
const companies = new Set()
console.log(companies)
```
```sh
Set(0) {}
```
### Creare un set da un array
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French',
]
const setOfLanguages = new Set(languages)
console.log(setOfLanguages)
```
```sh
Set(4) {"English", "Finnish", "French", "Spanish"}
```
Set è un oggetto iterabile e possiamo iterare attraverso ogni elemento.
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French',
]
const setOfLanguages = new Set(languages)
for (const language of setOfLanguages) {
console.log(language)
}
```
```sh
English
Finnish
French
Spanish
```
### Aggiungere un elemento ad un set
```js
const companies = new Set() // creating an empty set
console.log(companies.size) // 0
companies.add('Google') // add element to the set
companies.add('Facebook')
companies.add('Amazon')
companies.add('Oracle')
companies.add('Microsoft')
console.log(companies.size) // 5 elements in the set
console.log(companies)
```
```sh
Set(5) {"Google", "Facebook", "Amazon", "Oracle", "Microsoft"}
```
Possiamo anche usare il ciclo per aggiungere elementi a un insieme.
```js
const companies = ['Google', 'Facebook', 'Amazon', 'Oracle', 'Microsoft']
setOfCompanies = new Set()
for (const company of companies) {
setOfCompanies.add(company)
}
```
```sh
Set(5) {"Google", "Facebook", "Amazon", "Oracle", "Microsoft"}
```
### Eliminare un elemento dal set
Possiamo eliminare un elemento da un insieme utilizzando un metodo di cancellazione.
```js
console.log(companies.delete('Google'))
console.log(companies.size) // 4 elements left in the set
```
### Verificare la presenza di un elemento nel set
Il metodo has può aiutare a sapere se un certo elemento esiste in un insieme.
```js
console.log(companies.has('Apple')) // false
console.log(companies.has('Facebook')) // true
```
### Svuotare il set
Rimuove tutti gli elementi da un insieme.
```js
companies.clear()
console.log(companies)
```
```sh
Set(0) {}
```
Vedere l'esempio seguente per imparare a usare set.
```js
const languages = [
'English',
'Finnish',
'English',
'French',
'Spanish',
'English',
'French',
]
const langSet = new Set(languages)
console.log(langSet) // Set(4) {"English", "Finnish", "French", "Spanish"}
console.log(langSet.size) // 4
const counts = []
const count = {}
for (const l of langSet) {
const filteredLang = languages.filter((lng) => lng === l)
console.log(filteredLang) // ["English", "English", "English"]
counts.push({ lang: l, count: filteredLang.length })
}
console.log(counts)
```
```js
[
{ lang: 'English', count: 3 },
{ lang: 'Finnish', count: 1 },
{ lang: 'French', count: 2 },
{ lang: 'Spanish', count: 1 },
]
```
Altri casi d'uso di set. Ad esempio, per contare gli elementi unici di un array.
```js
const numbers = [5, 3, 2, 5, 5, 9, 4, 5]
const setOfNumbers = new Set(numbers)
console.log(setOfNumbers)
```
```sh
Set(5) {5, 3, 2, 9, 4}
```
### Unione di set
Per trovare l'unione di due insiemi si può utilizzare l'operatore di divisione. Troviamo l'unione dell'insieme A e dell'insieme B (A U B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let c = [...a, ...b]
let A = new Set(a)
let B = new Set(b)
let C = new Set(c)
console.log(C)
```
```sh
Set(6) {1, 2, 3, 4, 5,6}
```
### Intersezione di set
Per trovare l'intersezione di due insiemi si può utilizzare un filtro. Troviamo l'intersezione dell'insieme A e dell'insieme B (A ∩ B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let A = new Set(a)
let B = new Set(b)
let c = a.filter((num) => B.has(num))
let C = new Set(c)
console.log(C)
```
```sh
Set(3) {3, 4, 5}
```
### Differenza tra set
Per trovare la differenza tra due insiemi si può utilizzare un filtro. Troviamo la differenza tra l'insieme A e l'insieme B (A \ B)
```js
let a = [1, 2, 3, 4, 5]
let b = [3, 4, 5, 6]
let A = new Set(a)
let B = new Set(b)
let c = a.filter((num) => !B.has(num))
let C = new Set(c)
console.log(C)
```
```sh
Set(2) {1, 2}
```
## Map
### Creare un map vuoto
```js
const map = new Map()
console.log(map)
```
```sh
Map(0) {}
```
### Creare un map da un array
```js
countries = [
['Finland', 'Helsinki'],
['Sweden', 'Stockholm'],
['Norway', 'Oslo'],
]
const map = new Map(countries)
console.log(map)
console.log(map.size)
```
```sh
Map(3) {"Finland" => "Helsinki", "Sweden" => "Stockholm", "Norway" => "Oslo"}
3
```
### Aggiungere valori ad un map
```js
const countriesMap = new Map()
console.log(countriesMap.size) // 0
countriesMap.set('Finland', 'Helsinki')
countriesMap.set('Sweden', 'Stockholm')
countriesMap.set('Norway', 'Oslo')
console.log(countriesMap)
console.log(countriesMap.size)
```
```sh
Map(3) {"Finland" => "Helsinki", "Sweden" => "Stockholm", "Norway" => "Oslo"}
3
```
### Ottenere un valore dal map
```js
console.log(countriesMap.get('Finland'))
```
```sh
Helsinki
```
### Controllare le key del map
Controlla se una chiave esiste in una mappa usando il metodo _has_. Restituisce _true_ o _false_.
```js
console.log(countriesMap.has('Finland'))
```
```sh
true
```
Ottenere tutti i valori dalla mappa utilizzando il ciclo
```js
for (const country of countriesMap) {
console.log(country)
}
```
```sh
(2) ["Finland", "Helsinki"]
(2) ["Sweden", "Stockholm"]
(2) ["Norway", "Oslo"]
```
```js
for (const [country, city] of countriesMap){
console.log(country, city)
}
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
```
🌕 Hai raggiunto un grande traguardo, sei inarrestabile. Continua così! Hai appena completato le sfide del 10° giorno e sei a 10 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## Esercizi
### Esercizi: Livello 1
```js
const a = [4, 5, 8, 9]
const b = [3, 4, 5, 7]
const countries = ['Finland', 'Sweden', 'Norway']
```
1. creare un insieme vuoto
2. Creare un insieme contenente da 0 a 10 utilizzando il ciclo
3. Rimuovere un elemento da un insieme
4. Cancellare un insieme
5. Creare un insieme di 5 elementi stringa da un array
6. Creare una mappa di paesi e il numero di caratteri di un paese
### Esercizi: Livello 2
1. Trovare un'unione b
2. Trovare un'intersezione b
3. Trovare a con b
### Esercizi: Livello 3
1. Quante lingue sono presenti nel file oggetto Paesi.
1. \*\*\* Utilizzate i dati dei Paesi per trovare le 10 lingue più parlate:
```js
// Your output should look like this
console.log(mostSpokenLanguages(countries, 10))
[
{ English: 91 },
{ French: 45 },
{ Arabic: 25 },
{ Spanish: 24 },
{ Russian: 9 },
{ Portuguese: 9 },
{ Dutch: 8 },
{ German: 7 },
{ Chinese: 5 },
{ Swahili: 4 },
{ Serbian: 4 }
]
// Your output should look like this
console.log(mostSpokenLanguages(countries, 3))
[
{English:91},
{French:45},
{Arabic:25}
]
```
🎉 CONGRATULAZIONI ! 🎉
[<< Day 9](../09_Day_Higher_order_functions/09_day_higher_order_functions.md) | [Day 11 >>](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md)

@ -0,0 +1,699 @@
<div align="center">
<h1> 30 Days Of JavaScript: Destructuring and Spreading</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 10](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | [Day 12>>](../12_Day_Regular_expressions/12_day_regular_expressions.md)
![Day 11](../../images/banners/day_1_11.png)
- [Day 11](#day-11)
- [Destructuring e Spread](#destructuring-and-spread)
- [Destructing Arrays](#destructing-arrays)
- [Destructuring durante iterazione](#destructuring-during-iteration)
- [Object Destructuring](#destructuring-object)
- [Rinominare durante structuring](#renaming-during-structuring)
- [Object parameter senza destructuring](#object-parameter-without-destructuring)
- [Object parameter con destructuring](#object-parameter-with-destructuring)
- [Object Destructuring durante l'iterazione](#destructuring-object-during-iteration)
- [Spread o Rest Operator](#spread-or-rest-operator)
- [Operatore Spread per ottenere il resto degli elementi di un array](#spread-operator-to-get-the-rest-of-array-elements)
- [Operatore Spread per copiare un array](#spread-operator-to-copy-array)
- [Operatore Spread per copiare oggetti](#spread-operator-to-copy-object)
- [Operatore Spread con arrow function](#spread-operator-with-arrow-function)
- [Esercizi](#exercises)
- [Esercizi: Livello 1](#exercises-level-1)
- [Esercizi: Livello 2](#exercises-level-2)
- [Esercizi: Livello 3](#exercises-level-3)
# Day 11
## Destructuring e Spread
La destrutturazione è un modo per disimballare array e oggetti e assegnarli a una variabile distinta.
### Destructing Arrays
```js
const numbers = [1, 2, 3]
let [numOne, numTwo, numThree] = numbers
console.log(numOne, numTwo, numThree)
```
```sh
1 2 3
```
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
let [firstPerson, secondPerson, thirdPerson, fourthPerson] = names
console.log(firstPerson, secondPerson,thirdPerson, fourthPerson)
```
```sh
Asabeneh Brook David John
```
```js
const scientificConstants = [2.72, 3.14, 9.81, 37, 100]
let [e, pi, gravity, bodyTemp, boilingTemp] = scientificConstants
console.log(e,pi,gravity, bodyTemp, boilingTemp)
```
```sh
2.72 3.14 9.81 37 100
```
```js
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]
const [frontEnd, backEnd] = fullStack
console.log(frontEnd)
console.log(backEnd)
```
```sh
["HTML", "CSS", "JS", "React"]
["Node", "Express", "MongoDB"]
```
Se vogliamo saltare uno dei valori dell'array, usiamo una virgola aggiuntiva. La virgola aiuta a omettere il valore in quello specifico indice
```js
const numbers = [1, 2, 3]
let [numOne, , numThree] = numbers //2 is omitted
console.log(numOne, numThree)
```
```sh
1 3
```
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
let [, secondPerson, , fourthPerson] = names // first and third person is omitted
console.log(secondPerson, fourthPerson)
```
```sh
Brook John
```
È possibile utilizzare il valore predefinito nel caso in cui il valore dell'array per quell'indice sia indefinito:
```js
const names = [undefined, 'Brook', 'David']
let [
firstPerson = 'Asabeneh',
secondPerson,
thirdPerson,
fourthPerson = 'John'
] = names
console.log(firstPerson, secondPerson, thirdPerson, fourthPerson)
```
```sh
Asabeneh Brook David John
```
Non possiamo assegnare una variabile a tutti gli elementi dell'array. Possiamo destrutturare alcuni dei primi e ottenere i rimanenti come array utilizzando l'operatore spread(...).
```js
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [num1, num2, num3, ...rest] = nums
console.log(num1, num2, num3)
console.log(rest)
```
```sh
1 2 3
[4, 5, 6, 7, 8, 9, 10]
```
### Destructuring durante iterazione
```js
const countries = [['Finland', 'Helsinki'], ['Sweden', 'Stockholm'], ['Norway', 'Oslo']]
for (const [country, city] of countries) {
console.log(country, city)
}
```
```sh
Finland Helsinki
Sweden Stockholm
Norway Oslo
```
```js
const fullStack = [
['HTML', 'CSS', 'JS', 'React'],
['Node', 'Express', 'MongoDB']
]
for(const [first, second, third] of fullStack) {
console.log(first, second, third)
}
```
```sh
HTML CSS JS
Node Express MongoDB
```
### Object Destructuring
Quando si destruttura, il nome della variabile che si usa per destrutturare deve essere esattamente lo stesso della chiave o della proprietà dell'oggetto. Si veda l'esempio seguente.
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width, height, area, perimeter } = rectangle
console.log(width, height, area, perimeter)
```
```sh
20 10 200 undefined
```
### Rinominare durante structuring
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width: w, height: h, area: a, perimeter: p } = rectangle
console.log(w, h, a, p)
```
```sh
20 10 200 undefined
```
Se la chiave non viene trovata nell'oggetto, la variabile verrà assegnata a undefined. A volte la chiave potrebbe non essere presente nell'oggetto, in questo caso possiamo dare un valore predefinito durante la dichiarazione. Si veda l'esempio.
```js
const rectangle = {
width: 20,
height: 10,
area: 200
}
let { width, height, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //20 10 200 60
//Let us modify the object:width to 30 and perimeter to 80
```
```js
const rectangle = {
width: 30,
height: 10,
area: 200,
perimeter: 80
}
let { width, height, area, perimeter = 60 } = rectangle
console.log(width, height, area, perimeter) //30 10 200 80
```
Destrutturazione delle chiavi come parametri di una funzione. Creiamo una funzione che prende un oggetto rettangolo e restituisce il perimetro di un rettangolo.
### Object parameter senza destructuring
```js
// Without destructuring
const rect = {
width: 20,
height: 10
}
const calculatePerimeter = rectangle => {
return 2 * (rectangle.width + rectangle.height)
}
console.log(calculatePerimeter(rect)) // 60
//with destructuring
```
```js
//Another Example
const person = {
firstName: 'Asabeneh',
lastName: 'Yetayeh',
age: 250,
country: 'Finland',
job: 'Instructor and Developer',
skills: [
'HTML',
'CSS',
'JavaScript',
'React',
'Redux',
'Node',
'MongoDB',
'Python',
'D3.js'
],
languages: ['Amharic', 'English', 'Suomi(Finnish)']
}
// Let us create a function which give information about the person object without destructuring
const getPersonInfo = obj => {
const skills = obj.skills
const formattedSkills = skills.slice(0, -1).join(', ')
const languages = obj.languages
const formattedLanguages = languages.slice(0, -1).join(', ')
personInfo = `${obj.firstName} ${obj.lastName} lives in ${obj.country}. He is ${
obj.age
} years old. He is an ${obj.job}. He teaches ${formattedSkills} and ${
skills[skills.length - 1]
}. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo
}
console.log(getPersonInfo(person))
```
### Object parameter con destructuring
```js
const calculatePerimeter = ({ width, height }) => {
return 2 * (width + height)
}
console.log(calculatePerimeter(rect)) // 60
```
```js
// Let us create a function which give information about the person object with destructuring
const getPersonInfo = ({
firstName,
lastName,
age,
country,
job,
skills,
languages
}) => {
const formattedSkills = skills.slice(0, -1).join(', ')
const formattedLanguages = languages.slice(0, -1).join(', ')
personInfo = `${firstName} ${lastName} lives in ${country}. He is ${age} years old. He is an ${job}. He teaches ${formattedSkills} and ${
skills[skills.length - 1]
}. He speaks ${formattedLanguages} and a little bit of ${languages[2]}.`
return personInfo
}
console.log(getPersonInfo(person))
/*
Asabeneh Yetayeh lives in Finland. He is 250 years old. He is an Instructor and Developer. He teaches HTML, CSS, JavaScript, React, Redux, Node, MongoDB, Python and D3.js. He speaks Amharic, English and a little bit of Suomi(Finnish)
*/
```
### Object Destructuring durante l'iterazione
```js
const todoList = [
{
task:'Prepare JS Test',
time:'4/1/2020 8:30',
completed:true
},
{
task:'Give JS Test',
time:'4/1/2020 10:00',
completed:false
},
{
task:'Assess Test Result',
time:'4/1/2020 1:00',
completed:false
}
]
for (const {task, time, completed} of todoList){
console.log(task, time, completed)
}
```
```sh
Prepare JS Test 4/1/2020 8:30 true
Give JS Test 4/1/2020 10:00 false
Assess Test Result 4/1/2020 1:00 false
```
### Spread o Rest Operator
Quando destrutturiamo un array, utilizziamo l'operatore spread(...) per ottenere gli elementi rimanenti come array. Inoltre, utilizziamo l'operatore spread per distribuire gli elementi dell'array in un altro array.
### Operatore Spread per ottenere il resto degli elementi di un array
```js
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [num1, num2, num3, ...rest] = nums
console.log(num1, num2, num3)
console.log(rest)
```
```sh
1 2 3
[4, 5, 6, 7, 8, 9, 10]
```
```js
const countries = [
'Germany',
'France',
'Belgium',
'Finland',
'Sweden',
'Norway',
'Denmark',
'Iceland'
]
let [gem, fra, , ...nordicCountries] = countries
console.log(gem)
console.log(fra)
console.log(nordicCountries)
```
```sh
Germany
France
["Finland", "Sweden", "Norway", "Denmark", "Iceland"]
```
### Operatore Spread per copiare un array
```js
const evens = [0, 2, 4, 6, 8, 10]
const evenNumbers = [...evens]
const odds = [1, 3, 5, 7, 9]
const oddNumbers = [...odds]
const wholeNumbers = [...evens, ...odds]
console.log(evenNumbers)
console.log(oddNumbers)
console.log(wholeNumbers)
```
```sh
[0, 2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
[0, 2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
```
```js
const frontEnd = ['HTML', 'CSS', 'JS', 'React']
const backEnd = ['Node', 'Express', 'MongoDB']
const fullStack = [...frontEnd, ...backEnd]
console.log(fullStack)
```
```sh
["HTML", "CSS", "JS", "React", "Node", "Express", "MongoDB"]
```
### Operatore Spread per copiare oggetti
Possiamo copiare un oggetto usando un operatore di diffusione
```js
const user = {
name:'Asabeneh',
title:'Programmer',
country:'Finland',
city:'Helsinki'
}
const copiedUser = {...user}
console.log(copiedUser)
```
```sh
{name: "Asabeneh", title: "Programmer", country: "Finland", city: "Helsinki"}
```
Modificare o cambiare l'oggetto durante la copia
```js
const user = {
name:'Asabeneh',
title:'Programmer',
country:'Finland',
city:'Helsinki'
}
const copiedUser = {...user, title:'instructor'}
console.log(copiedUser)
```
```sh
{name: "Asabeneh", title: "instructor", country: "Finland", city: "Helsinki"}
```
#### Operatore Spread con arrow function
Ogni volta che vogliamo scrivere una funzione che accetta un numero illimitato di argomenti, utilizziamo l'operatore spread. Se utilizziamo un operatore di diffusione come parametro, l'argomento passato quando invochiamo una funzione si trasformerà in un array.
```js
const sumAllNums = (...args) => {
console.log(args)
}
sumAllNums(1, 2, 3, 4, 5)
```
```sh
[1, 2, 3, 4, 5]
```
```js
const sumAllNums = (...args) => {
let sum = 0
for (const num of args){
sum += num
}
return sum
}
console.log(sumAllNums(1, 2, 3, 4, 5))
```
```sh
15
```
🌕 Finora hai ottenuto molti risultati. Ora il tuo livello di JavaScript è intermedio. Continua così! Sei appena completato le sfide dell'undicesimo giorno e sei a 11 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## Esercizi
### Esercizi: Livello 1
```js
const constants = [2.72, 3.14, 9.81, 37, 100]
const countries = ['Finland', 'Estonia', 'Sweden', 'Denmark', 'Norway']
const rectangle = {
width: 20,
height: 10,
area: 200,
perimeter: 60
}
const users = [
{
name:'Brook',
scores:75,
skills:['HTM', 'CSS', 'JS'],
age:16
},
{
name:'Alex',
scores:80,
skills:['HTM', 'CSS', 'JS'],
age:18
},
{
name:'David',
scores:75,
skills:['HTM', 'CSS'],
age:22
},
{
name:'John',
scores:85,
skills:['HTML'],
age:25
},
{
name:'Sara',
scores:95,
skills:['HTM', 'CSS', 'JS'],
age: 26
},
{
name:'Martha',
scores:80,
skills:['HTM', 'CSS', 'JS'],
age:18
},
{
name:'Thomas',
scores:90,
skills:['HTM', 'CSS', 'JS'],
age:20
}
]
```
1. Destrutturare e assegnare gli elementi dell'array di costanti a e, pi greco, gravità, humanBodyTemp, waterBoilingTemp.
2. Destrutturare e assegnare gli elementi dell'array countries a fin, est, sw, den, nor.
3. Destrutturare l'oggetto rettangolo in base alle sue proprietà o chiavi.
### Esercizi: Livello 2
1. Iterare l'array degli utenti e ottenere tutte le chiavi dell'oggetto utilizzando la destrutturazione.
2. Trovare le persone che hanno meno di due competenze
### Esercizi: Livello 3
1. Destrutturare l'oggetto Paesi stampare nome, capitale, popolazione e lingua di tutti i Paesi.
2. Uno sviluppatore junior struttura il nome dello studente, le competenze e il punteggio in array di array che potrebbero non essere facili da leggere. Destrutturare il seguente array nome in nome, l'array delle competenze in competenze, l'array dei punteggi in punteggi, il punteggio JavaScript in jsScore e il punteggio React in reactScore in una riga.
```js
const student = ['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]]
console.log(name, skills, jsScore, reactScore)
```
```sh
David (4) ["HTM", "CSS", "JS", "React"] 90 95
```
3. Scrivete una funzione chiamata *convertArrayToObject* in grado di convertire l'array in un oggetto struttura.
```js
const students = [
['David', ['HTM', 'CSS', 'JS', 'React'], [98, 85, 90, 95]],
['John', ['HTM', 'CSS', 'JS', 'React'], [85, 80, 85, 80]]
]
console.log(convertArrayToObject(students))
[
{
name: 'David',
skills: ['HTM','CSS','JS','React'],
scores: [98,85,90,95]
},
{
name: 'John',
skills: ['HTM','CSS','JS','React'],
scores: [85, 80,85,80]
}
]
```
4. Copiare l'oggetto studente in newStudent senza mutare l'oggetto originale. Nel nuovo oggetto aggiungere il seguente ?
- Aggiungere Bootstrap con Livello 8 ai set di competenze del front end.
- Aggiungere Express con Livello 9 ai set di competenze del back end.
- Aggiungere SQL con Livello 8 ai set di competenze della base dati.
- Aggiungere SQL senza Livello ai set di competenze di scienza dei dati.
```js
const student = {
name: 'David',
age: 25,
skills: {
frontEnd: [
{ skill: 'HTML', level: 10 },
{ skill: 'CSS', level: 8 },
{ skill: 'JS', level: 8 },
{ skill: 'React', level: 9 }
],
backEnd: [
{ skill: 'Node',level: 7 },
{ skill: 'GraphQL', level: 8 },
],
dataBase:[
{ skill: 'MongoDB', level: 7.5 },
],
dataScience:['Python', 'R', 'D3.js']
}
}
```
L'output dell'oggetto copiato dovrebbe essere simile a questo:
```js
{
name: 'David',
age: 25,
skills: {
frontEnd: [
{skill: 'HTML',level: 10},
{skill: 'CSS',level: 8},
{skill: 'JS',level: 8},
{skill: 'React',level: 9},
{skill: 'BootStrap',level: 8}
],
backEnd: [
{skill: 'Node',level: 7},
{skill: 'GraphQL',level: 8},
{skill: 'Express',level: 9}
],
dataBase: [
{ skill: 'MongoDB',level: 7.5},
{ skill: 'SQL',level: 8}
],
dataScience: ['Python','R','D3.js','SQL']
}
}
```
🎉 CONGRATULAZIONI ! 🎉
[<< Day 10](../10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | [Day 12 >>](../12_Day_Regular_expressions/12_day_regular_expressions.md)

@ -0,0 +1,536 @@
<div align="center">
<h1> 30 Days Of JavaScript: Regular Expressions</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 11](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | [Day 13>>](../13_Day_Console_object_methods/13_day_console_object_methods.md)
![Thirty Days Of JavaScript](../../images/banners/day_1_12.png)
- [📘 Day 12](#-day-12)
- [Espressioni Regolari](#regular-expressions)
- [Parameteri RegExp](#regexp-parameters)
- [Pattern](#pattern)
- [Flags](#flags)
- [Creare un pattern con il costruttore RegExp](#creating-a-pattern-with-regexp-constructor)
- [Creare un pattern senza il costruttore RegExp](#creating-a-pattern-without-regexp-constructor)
- [Metodi dell'oggetto RegExp](#regexpp-object-methods)
- [Testing per un match](#testing-for--a-match)
- [Array contenente tutto il match](#array-containing-all-of-the-match)
- [Sostituire una substring](#replacing-a-substring)
- [Square Bracket (parentesi quadra)](#square-bracket)
- [Escape character(\\) in RegExp](#escape-character-in-regexp)
- [Uno o più volte(+)](#one-or-more-times)
- [Period(.)](#period)
- [Zero o più volte(*)](#zero-or-more-times)
- [Zero oppure una volta(?)](#zero-or-one-times)
- [Quantifier in RegExp](#quantifier-in-regexp)
- [Cart ^](#cart-)
- [Match esatto](#exact-match)
- [💻 Esercizi](#-exercises)
- [Esercizi: Livello 1](#exercises-level-1)
- [Esercizi: Livello 2](#exercises-level-2)
- [Esercizi: Livello 3](#exercises-level-3)
# 📘 Day 12
## Espressioni Regolari
Un'espressione regolare o RegExp è un piccolo linguaggio di programmazione che aiuta a trovare modelli nei dati. Una RegExp può essere usata per verificare se un certo modello esiste in diversi tipi di dati. Per usare le RegExp in JavaScript si può usare il costruttore RegExp oppure si può dichiarare un modello RegExp usando due barre in avanti seguite da un flag. Possiamo creare un modello in due modi.
Per dichiarare una stringa si usano una virgoletta singola, una doppia virgoletta e un backtick, mentre per dichiarare un'espressione regolare si usano due barre in avanti e un flag opzionale. Il flag può essere g, i, m, s, u o y.
### Parameteri RegExp
Un'espressione regolare richiede due parametri. Un modello di ricerca richiesto e un parametron optional flag.
#### Pattern
Un modello può essere un testo o una qualsiasi forma di modello che presenta una qualche somiglianza. Per esempio, la parola spam in un'e-mail potrebbe essere un modello che ci interessa cercare in un'e-mail o un numero di telefono in formato numero potrebbe essere il nostro interesse da cercare.
#### Flags
I flag sono parametri opzionali di un'espressione regolare che determinano il tipo di ricerca. Vediamo alcuni dei flag:
- g: un flag globale che significa cercare un modello in tutto il testo
- i: flag di insensibilità alle maiuscole (cerca sia le minuscole che le maiuscole)
- m: multilinea
### Creare un pattern con il costruttore RegExp
Dichiarare un'espressione regolare senza flag globale e senza flag case insensitive.
```js
// without flag
let pattern = 'love'
let regEx = new RegExp(pattern)
```
Dichiarazione di un'espressione regolare con flag globale e flag case insensitive.
```js
let pattern = 'love'
let flag = 'gi'
let regEx = new RegExp(pattern, flag)
```
Dichiarare un modello regex usando l'oggetto RegExp. Scrittura del pattern e del flag all'interno del costruttore RegExp
```js
let regEx = new RegExp('love','gi')
```
### Creare un pattern senza il costruttore RegExp
Dichiarazione di un'espressione regolare con flag globale e flag case insensitive.
```js
let regEx= /love/gi
```
L'espressione regolare di cui sopra è uguale a quella creata con il costruttore RegExp
```js
let regEx= new RegExp('love','gi')
```
### Metodi dell'oggetto RegExp
Vediamo alcuni metodi di RegExp
#### Testing per un match
*test()*: Verifica la presenza di una corrispondenza in una stringa. Restituisce vero o falso.
```js
const str = 'I love JavaScript'
const pattern = /love/
const result = pattern.test(str)
console.log(result)
```
```sh
true
```
#### Array contenente tutto il match
*match()*: Restituisce un array contenente tutte le corrispondenze, compresi i gruppi di cattura, oppure null se non viene trovata alcuna corrispondenza.
Se non si utilizza un flag globale, match() restituisce un array contenente il pattern, l'indice, l'input e il gruppo.
```js
const str = 'I love JavaScript'
const pattern = /love/
const result = str.match(pattern)
console.log(result)
```
```sh
["love", index: 2, input: "I love JavaScript", groups: undefined]
```
```js
const str = 'I love JavaScript'
const pattern = /love/g
const result = str.match(pattern)
console.log(result)
```
```sh
["love"]
```
*search()*: Cerca una corrispondenza in una stringa. Restituisce l'indice della corrispondenza o -1 se la ricerca fallisce.
```js
const str = 'I love JavaScript'
const pattern = /love/g
const result = str.search(pattern)
console.log(result)
```
```sh
2
```
#### Sostituire una substring
*replace()*: Esegue la ricerca di una corrispondenza in una stringa e sostituisce la sottostringa corrispondente con una sostitutiva.
```js
const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'
matchReplaced = txt.replace(/Python|python/, 'JavaScript')
console.log(matchReplaced)
```
```sh
JavaScript is the most beautiful language that a human begin has ever created.I recommend python for a first programming language
```
```js
const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'
matchReplaced = txt.replace(/Python|python/g, 'JavaScript')
console.log(matchReplaced)
```
```sh
JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language
```
```js
const txt = 'Python is the most beautiful language that a human begin has ever created.\
I recommend python for a first programming language'
matchReplaced = txt.replace(/Python/gi, 'JavaScript')
console.log(matchReplaced)
```
```sh
JavaScript is the most beautiful language that a human begin has ever created.I recommend JavaScript for a first programming language
```
```js
const txt = '%I a%m te%%a%%che%r% a%n%d %% I l%o%ve te%ach%ing.\
T%he%re i%s n%o%th%ing as m%ore r%ewarding a%s e%duc%at%i%ng a%n%d e%m%p%ow%er%ing \
p%e%o%ple.\
I fo%und te%a%ching m%ore i%n%t%er%%es%ting t%h%an any other %jobs.\
D%o%es thi%s m%ot%iv%a%te %y%o%u to b%e a t%e%a%cher.'
matches = txt.replace(/%/g, '')
console.log(matches)
```
```sh
I am teacher and I love teaching.There is nothing as more rewarding as educating and empowering people.I found teaching more interesting than any other jobs.Does this motivate you to be a teacher.
```
* []: Un insieme di caratteri
* [a-c] significa, a o b o c
* [a-z] significa, qualsiasi lettera da a a z
* [A-Z] significa qualsiasi carattere dalla A alla Z
* [0-3] significa, 0 o 1 o 2 o 3
* [0-9] significa qualsiasi numero da 0 a 9
* [A-Za-z0-9] qualsiasi carattere dalla a alla z, dalla A alla Z, da 0 a 9
* \\: utilizza per sfuggire a caratteri speciali
* \d significa: corrisponde se la stringa contiene cifre (numeri da 0-9)
* \D significa: corrispondere a una stringa che non contiene cifre
* . : qualsiasi carattere tranne il carattere di nuova riga (\n)
* ^: inizia con
* r'^substring' eg r'^love', una frase che inizia con la parola amore
* r'[^abc] significa non a, non b, non c.
* $: finisce con
* r'substring$' eg r'love$', la frase termina con una parola amore
* *: zero o più volte
* r'[a]*' significa un optional o può verificarsi più volte.
* +: una o più volte
* r'[a]+' significa almeno una o più volte
* ?: zero o più volte
* r'[a]?' significa zero o una volta
* \b: delimitatore di parole, corrisponde all'inizio o alla fine di una parola
* {3}: Esattamente 3 caratteri
* {3,}: Almeno 3 caratteri
* {3,8}: Da 3 a 8 caratteri
* |: operatore or
* r'apple|banana' significa sia di una mela che di una banana
* (): Cattura e raggruppa
![Regular Expression cheat sheet](../../images/regex.png)
Utilizziamo un esempio per chiarire i meta-caratteri di cui sopra
### Square Bracket (parentesi quadra)
Utilizziamo la parentesi quadra per includere le lettere minuscole e maiuscole
```js
const pattern = '[Aa]pple' // this square bracket means either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day keeps the doctor way has been replaced by a banana a day keeps the doctor far far away. '
const matches = txt.match(pattern)
console.log(matches)
```
```sh
["Apple", index: 0, input: "Apple and banana are fruits. An old cliche says an apple a day keeps the doctor way has been replaced by a banana a day keeps the doctor far far away.", groups: undefined]
```
```js
const pattern = /[Aa]pple/g // this square bracket means either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. '
const matches = txt.match(pattern)
console.log(matches)
```
```sh
["Apple", "apple"]
```
Se vogliamo cercare la banana, scriviamo lo schema come segue:
```js
const pattern = /[Aa]pple|[Bb]anana/g // this square bracket mean either A or a
const txt = 'Apple and banana are fruits. An old cliche says an apple a day a doctor way has been replaced by a banana a day keeps the doctor far far away. Banana is easy to eat too.'
const matches = txt.match(pattern)
console.log(matches)
```
```sh
["Apple", "banana", "apple", "banana", "Banana"]
```
Utilizzando la parentesi quadra e l'operatore o , riusciamo a estrarre Apple, apple, Banana e banana.
### Escape character(\\) in RegExp
```js
const pattern = /\d/g // d is a special character which means digits
const txt = 'This regular expression example was made in January 12, 2020.'
const matches = txt. match(pattern)
console.log(matches) // ["1", "2", "2", "0", "2", "0"], this is not what we want
```
```js
const pattern = /\d+/g // d is a special character which means digits
const txt = 'This regular expression example was made in January 12, 2020.'
const matches = txt. match(pattern)
console.log(matches) // ["12", "2020"], this is not what we want
```
### Uno o più volte(+)
```js
const pattern = /\d+/g // d is a special character which means digits
const txt = 'This regular expression example was made in January 12, 2020.'
const matches = txt. match(pattern)
console.log(matches) // ["12", "2020"], this is not what we want
```
### Period(.)
```js
const pattern = /[a]./g // this square bracket means a and . means any character except new line
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)
console.log(matches) // ["an", "an", "an", "a ", "ar"]
```
```js
const pattern = /[a].+/g // . any character, + any character one or more times
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)
console.log(matches) // ['and banana are fruits']
```
### Zero o più volte(*)
Zero o molte volte. Il modello può non verificarsi o verificarsi più volte.
```js
const pattern = /[a].*/g //. any character, + any character one or more times
const txt = 'Apple and banana are fruits'
const matches = txt.match(pattern)
console.log(matches) // ['and banana are fruits']
```
### Zero oppure una volta(?)
Zero o una volta. Il modello può non verificarsi o verificarsi una volta.
```js
const txt = 'I am not sure if there is a convention how to write the word e-mail.\
Some people write it email others may write it as Email or E-mail.'
const pattern = /[Ee]-?mail/g // ? means optional
matches = txt.match(pattern)
console.log(matches) // ["e-mail", "email", "Email", "E-mail"]
```
### Quantifier in RegExp
Possiamo specificare la lunghezza della sottostringa che cerchiamo in un testo, utilizzando una parentesi graffa. Vediamo come utilizzare i quantificatori RegExp. Immaginiamo di essere interessati a una sottostringa la cui lunghezza sia di 4 caratteri
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\\b\w{4}\b/g // exactly four character words
const matches = txt.match(pattern)
console.log(matches) //['This', 'made', '2019']
```
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\b[a-zA-Z]{4}\b/g // exactly four character words without numbers
const matches = txt.match(pattern)
console.log(matches) //['This', 'made']
```
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\d{4}/g // a number and exactly four digits
const matches = txt.match(pattern)
console.log(matches) // ['2019']
```
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /\d{1,4}/g // 1 to 4
const matches = txt.match(pattern)
console.log(matches) // ['6', '2019']
```
### Cart ^
- Starts with
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /^This/ // ^ means starts with
const matches = txt.match(pattern)
console.log(matches) // ['This']
```
- Negation
```js
const txt = 'This regular expression example was made in December 6, 2019.'
const pattern = /[^A-Za-z,. ]+/g // ^ in set character means negation, not A to Z, not a to z, no space, no comma no period
const matches = txt.match(pattern)
console.log(matches) // ["6", "2019"]
```
### Match esatto
It should have ^ starting and $ which is an end.
```js
let pattern = /^[A-Z][a-z]{3,12}$/;
let name = 'Asabeneh';
let result = pattern.test(name)
console.log(result) // true
```
🌕 Stai andando lontano. Continuate così! Ora sei super caricato con il potere delle espressioni regolari. Hai il potere di estrarre e pulire qualsiasi tipo di testo e puoi ricavare un significato dai dati non strutturati. Hai appena completato le sfide del 12° giorno e sei a 12 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## 💻 Esercizi
### Esercizi: Livello 1
1. Calcolate il reddito totale annuo della persona che si trova nel testo seguente. 'Guadagna 4000 euro di stipendio al mese, 10000 euro di bonus annuale, 5500 euro di corsi online al mese.'
1. La posizione di alcune particelle sull'asse orizzontale x -12, -4, -3 e -1 in direzione negativa, 0 nell'origine, 4 e 8 in direzione positiva. Estraete questi numeri e trovate la distanza tra le due particelle più lontane.
```js
points = ['-1', '2', '-4', '-3', '-1', '0', '4', '8']
sortedPoints = [-4, -3, -1, -1, 0, 2, 4, 8]
distance = 12
```
1. Scrivere un modello che identifichi se una stringa è una variabile JavaScript valida.
```sh
is_valid_variable('first_name') # True
is_valid_variable('first-name') # False
is_valid_variable('1first_name') # False
is_valid_variable('firstname') # True
```
### Esercizi: Livello 2
1. Scrivere una funzione chiamata *tenMostFrequentWords* che ottenga le dieci parole più frequenti da una stringa?
```js
paragraph = `I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.`
console.log(tenMostFrequentWords(paragraph))
```
```sh
[
{word:'love', count:6},
{word:'you', count:5},
{word:'can', count:3},
{word:'what', count:2},
{word:'teaching', count:2},
{word:'not', count:2},
{word:'else', count:2},
{word:'do', count:2},
{word:'I', count:2},
{word:'which', count:1},
{word:'to', count:1},
{word:'the', count:1},
{word:'something', count:1},
{word:'if', count:1},
{word:'give', count:1},
{word:'develop',count:1},
{word:'capabilities',count:1},
{word:'application', count:1},
{word:'an',count:1},
{word:'all',count:1},
{word:'Python',count:1},
{word:'If',count:1}]
```
```js
console.log(tenMostFrequentWords(paragraph, 10))
```
```sh
[{word:'love', count:6},
{word:'you', count:5},
{word:'can', count:3},
{word:'what', count:2},
{word:'teaching', count:2},
{word:'not', count:2},
{word:'else', count:2},
{word:'do', count:2},
{word:'I', count:2},
{word:'which', count:1}
]
```
### Esercizi: Livello 3
1. Scrivere una funzione che pulisca il testo. Pulire il testo seguente. Dopo la pulizia, contare le tre parole più frequenti nella stringa.
```js
sentence = `%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?`
console.log(cleanText(sentence))
```
```sh
I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher
```
2. Scrivere una funzione che trovi le parole più frequenti. Dopo la pulizia, contare le tre parole più frequenti nella stringa.
```js
console.log(mostFrequentWords(cleanedText))
[{word:'I', count:3}, {word:'teaching', count:2}, {word:'teacher', count:2}]
```
🎉 CONGRATULAZIONI ! 🎉
[<< Day 11](../11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | [Day 13 >>](../13_Day_Console_object_methods/13_day_console_object_methods.md)

@ -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)
![Thirty Days Of JavaScript](../../images/banners/day_1_13.png)
- [Day 13](#day-13)
- [Metodi Oggetto Console](#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
## Metodi Oggetto Console
In questa sezione tratteremo i metodi della console e dell'oggetto console. I principianti assoluti di solito non sanno quale usare: console.log(), document.write() o document.getElementById.
Utilizziamo i metodi degli oggetti console per mostrare l'output sulla console del browser e document.write per mostrare l'output sul documento del browser (porta di visualizzazione). Entrambi i metodi sono utilizzati solo per scopi di test e debug. Il metodo console è lo strumento di test e debug più diffuso nel browser. Utilizziamo document.getElementById() quando vogliamo interagire con il DOM utilizzando JavaScript. Tratteremo il DOM in un'altra sezione.
Oltre al famoso metodo console.log(), la console fornisce altri metodi.
### console.log()
Usiamo console.log() per mostrare l'output sulla console del browser. Possiamo sostituire i valori e anche stilizzare il log con %c.
- Mostrare l'output sulla console del browser
```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
Possiamo stilizzare il messaggio di registrazione usando i css. Copiare il codice seguente e incollarlo nella console del browser per vedere il risultato.
```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()
Utilizziamo console.warn() per fornire avvisi al browser. Per esempio, per informare o avvisare della deprecazione di una versione di un pacchetto o di cattive pratiche. Copiate il codice seguente e incollatelo nella console del browser per visualizzare i messaggi di avviso.
```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()
Il metodo console.error() mostra un messaggio di errore.
```js
console.error('This is an error message')
console.error('We all make mistakes')
```
### console.table()
Il metodo console.table() visualizza i dati come tabella sulla console. Visualizza i dati in forma di tabella. Il metodo console.table() accetta un parametro obbligatorio, data, che deve essere un array o un oggetto, e un parametro opzionale aggiuntivo columns.
Cominciamo con un semplice array. Il codice seguente visualizza una tabella con due colonne. Una colonna indice per visualizzare l'indice e una colonna valore per visualizzare i nomi.
```js
const names = ['Asabeneh', 'Brook', 'David', 'John']
console.table(names)
```
Controlliamo anche il risultato di un oggetto. Si crea una tabella con due colonne: una colonna indice contenente le chiavi e una colonna valore contenente i valori dell'oggetto.
```js
const user = {
name: 'Asabeneh',
title: 'Programmer',
country: 'Finland',
city: 'Helsinki',
age: 250
}
console.table(user)
```
Verificate il resto degli esempi copiando e incollando sulla console del browser.
```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()
Avvia un timer che può essere utilizzato per tenere traccia del tempo necessario per un'operazione. A ogni timer viene assegnato un nome univoco e si possono avere fino a 10.000 timer in esecuzione su una data pagina. Quando si chiama console.timeEnd() con lo stesso nome, il browser visualizza il tempo, in millisecondi, trascorso dall'avvio del timer.
```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
```
Secondo l'output sopra riportato, il ciclo for regolare è più lento del ciclo for of o forEach.
### console.info()
Visualizza un messaggio informativo sulla console del browser.
```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()
Il metodo console.assert() scrive un messaggio di errore nella console se l'asserzione è falsa. Se l'asserzione è vera, non succede nulla. Il primo parametro è un'espressione di asserzione. Se questa espressione è falsa, viene visualizzato un messaggio di errore Asserzione fallita.
```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()
Console.group() può aiutare a raggruppare diversi gruppi di log. Copiare il codice seguente e incollarlo nella console del browser per i gruppi.
```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()
Stampa il numero di volte in cui viene richiamato console.count(). Richiede un parametro stringa label. È molto utile per contare il numero di volte che una funzione viene chiamata. Nell'esempio seguente, il metodo console.count() verrà eseguito tre volte
```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()
Console.clear() pulisce la console del browser.
🌕 Continua a lavorare bene. Continua a spingere, il cielo è il limite! Hai appena completato le sfide del 13° giorno e sei a 13 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## Esercizi
### Esercizi:Level 1
1. Visualizzare l'array di paesi come tabella
2. Visualizzare l'oggetto Paesi come tabella
3. Usare console.group() per raggruppare i log.
### Esercizi:Livello 2
1. 10 > 2 \* 10 usare console.assert()
2. Scrivere un messaggio di avviso usando console.warn()
3. Scrivere un messaggio di errore usando console.error()
### Esercizi:Level 3
1. Verificare la differenza di velocità tra i seguenti cicli: 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_14.png)
- [Day 14](#day-14)
- [Gestione Errori](#error-handling)
- [Tipi di Errore](#error-types)
- [Esercizi](#exercises)
- [Esercizi:Level 1](#exerciseslevel-1)
- [Esercizi: Livello 2](#exercises-level-2)
- [Esercizi:Level](#exerciseslevel)
# Day 14
## Gestione Errori
JavaScript è un linguaggio a tipizzazione libera. A volte si ottiene un errore di runtime quando si tenta di accedere a una variabile non definita o di chiamare una funzione non definita, ecc.
JavaScript, simile a Python o Java, fornisce un meccanismo di gestione degli errori per catturare gli errori di runtime utilizzando il blocco try-catch-finally.
```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
}
```
L'istruzione *try* ci permette di definire un blocco di codice che deve essere testato per verificare la presenza di errori durante l'esecuzione.
**catch**: scrivere il codice per fare qualcosa nel blocco catch quando si verifica un errore. Il blocco catch può avere dei parametri che forniscono informazioni sull'errore. Il blocco catch viene utilizzato per registrare un errore o per visualizzare messaggi specifici all'utente.
**finally**: il blocco finally viene sempre eseguito, indipendentemente dal verificarsi di un errore. Il blocco finally può essere usato per completare il compito rimanente o per resettare le variabili che potrebbero essere cambiate prima del verificarsi dell'errore nel blocco try.
**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
```
Il blocco catch accetta un parametro. È comune passare e, err o error come parametro al blocco catch. Questo parametro è un oggetto e ha le chiavi name e message. Utilizziamo il nome e il messaggio.
```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: l'istruzione throw consente di creare un errore personalizzato. Possiamo utilizzare una stringa, un numero, un booleano o un oggetto. Utilizzare l'istruzione throw per lanciare un'eccezione. Quando si lancia un'eccezione, l'espressione specifica il valore dell'eccezione. Ognuno dei seguenti comandi lancia un'eccezione:
```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()
```
### Tipi di Errore
- ReferenceError: Si è verificato un riferimento illegale. Un ReferenceError viene lanciato se si utilizza una variabile che non è stata dichiarata.
```js
let firstName = 'Asabeneh'
let fullName = firstName + ' ' + lastName
console.log(fullName)
```
```sh
Uncaught ReferenceError: lastName is not defined
at <anonymous>:2:35
```
- SyntaxError: Si è verificato un errore di sintassi
```js
let square = 2 x 2
console.log(square)
console.log('Hello, world")
```
```sh
Uncaught SyntaxError: Unexpected identifier
```
- TypeError: Si è verificato un errore di tipo
```js
let num = 10
console.log(num.toLowerCase())
```
```sh
Uncaught TypeError: num.toLowerCase is not a function
at <anonymous>:2:17
```
Questi sono alcuni degli errori più comuni che si possono incontrare quando si scrive un codice. Capire gli errori può aiutarvi a capire quali sono gli errori commessi e vi aiuterà a eseguire il debug del codice in modo rapido.
🌕 Sei impeccabile. Ora sai come gestire gli errori e sei in grado di scrivere applicazioni robuste che gestiscono gli input inaspettati dell'utente. Hai appena completato le sfide del giorno 14 e sei a 14 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## Esercizi
### Esercizi:Level 1
Fai pratica
### Esercizi: Livello 2
Fai pratica
### Esercizi:Level
Fai pratica
🎉 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,715 @@
<div align="center">
<h1> 30 Days Of JavaScript: Classes</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 14](../14_Day_Error_handling/14_day_error_handling.md) | [Day 16>>](../16_Day_JSON/16_day_json.md)
![Thirty Days Of JavaScript](../../images/banners/day_1_15.png)
- [Day 15](#day-15)
- [Classi](#classes)
- [Definire una classe](#defining-a-classes)
- [Instanzionare una Classe](#class-instantiation)
- [Costruttore della Classe](#class-constructor)
- [Valori di Default nel costruttore](#default-values-with-constructor)
- [Metodi di Classe](#class-methods)
- [Proprietà con valori iniziali](#properties-with-initial-value)
- [getter](#getter)
- [setter](#setter)
- [Metodo Statico](#static-method)
- [Inheritance (Ereditarietà)](#inheritance)
- [Override dei metodi](#overriding-methods)
- [Esercizi](#exercises)
- [Esercizi Livello 1](#exercises-level-1)
- [Esercizi Livello 2](#exercises-level-2)
- [Esercizi Livello 3](#exercises-level-3)
# Day 15
## Classi
JavaScript è un linguaggio di programmazione orientato agli oggetti. Tutto in JavaScript è un oggetto, con le sue proprietà e i suoi metodi. Per creare un oggetto, creiamo una classe. Una classe è come un costruttore di oggetti, o un "progetto" per la creazione di oggetti. Istanziamo una classe per creare un oggetto. La classe definisce gli attributi e il comportamento dell'oggetto, mentre l'oggetto, d'altra parte, rappresenta la classe.
Una volta creata una classe, possiamo creare oggetti da essa ogni volta che vogliamo. La creazione di un oggetto da una classe si chiama istanziazione della classe.
Nella sezione dedicata agli oggetti, abbiamo visto come creare un letterale di oggetto. L'oggetto letterale è un singleton. Se vogliamo ottenere un oggetto simile, dobbiamo scriverlo. Tuttavia, le classi consentono di creare molti oggetti. Questo aiuta a ridurre la quantità di codice e la sua ripetizione.
### Definire una classe
Per definire una classe in JavaScript è necessaria la parola chiave _class_, il nome della classe in **CamelCase** e il codice di blocco (due parentesi graffe). Creiamo una classe di nome Persona.
```sh
// syntax
class ClassName {
// code goes here
}
```
**Esempio:**
```js
class Person {
// code goes here
}
```
Abbiamo creato una classe Person, ma non ha nulla al suo interno.
### Instanzionare una Classe
Istanziare una classe significa creare un oggetto da una classe. Abbiamo bisogno della parola chiave _new_ e chiamiamo il nome della classe dopo la parola new.
Creiamo un oggetto cane dalla nostra classe Persona.
```js
class Person {
// code goes here
}
const person = new Person()
console.log(person)
```
```sh
Person {}
```
Come si può vedere, abbiamo creato un oggetto persona. Poiché la classe non ha ancora alcuna proprietà, anche l'oggetto è vuoto.
Utilizziamo il costruttore della classe per passare diverse proprietà alla classe.
### Costruttore della Classe
Il costruttore è una funzione integrata che consente di creare un blueprint per il nostro oggetto. La funzione costruttore inizia con la parola chiave constructor seguita da una parentesi. All'interno della parentesi si passano le proprietà dell'oggetto come parametro. Utilizziamo la parola chiave _this_ per associare i parametri del costruttore alla classe.
Il seguente costruttore della classe Person ha le proprietà firstName e lastName. Queste proprietà sono allegate alla classe Person utilizzando la parola chiave _this_. _This_ si riferisce alla classe stessa.
```js
class Person {
constructor(firstName, lastName) {
console.log(this) // Check the output from here
this.firstName = firstName
this.lastName = lastName
}
}
const person = new Person()
console.log(person)
```
```sh
Person {firstName: undefined, lastName:undefined}
```
Tutte le chiavi dell'oggetto sono indefinite. Quando si istanzia l'oggetto, si deve passare il valore delle proprietà. Passiamo il valore in questo momento, quando istanziamo la classe.
```js
class Person {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}
const person1 = new Person('Asabeneh', 'Yetayeh')
console.log(person1)
```
```sh
Person {firstName: "Asabeneh", lastName: "Yetayeh"}
```
Come abbiamo detto all'inizio, una volta creata una classe, possiamo creare molti oggetti utilizzando la classe. Ora, creiamo molti oggetti persona usando la classe Person.
```js
class Person {
constructor(firstName, lastName) {
console.log(this) // Check the output from here
this.firstName = firstName
this.lastName = lastName
}
}
const person1 = new Person('Asabeneh', 'Yetayeh')
const person2 = new Person('Lidiya', 'Tekle')
const person3 = new Person('Abraham', 'Yetayeh')
console.log(person1)
console.log(person2)
console.log(person3)
```
```sh
Person {firstName: "Asabeneh", lastName: "Yetayeh"}
Person {firstName: "Lidiya", lastName: "Tekle"}
Person {firstName: "Abraham", lastName: "Yetayeh"}
```
Utilizzando la classe Persona abbiamo creato tre oggetti persona. Come si può vedere, la nostra classe non ha molte proprietà, ma possiamo aggiungere altre proprietà alla classe.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
console.log(this) // Check the output from here
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
console.log(person1)
```
```sh
Person {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki"}
```
### Valori di Default nel costruttore
Le proprietà della funzione costruttore possono avere un valore predefinito come le altre funzioni regolari.
```js
class Person {
constructor(
firstName = 'Asabeneh',
lastName = 'Yetayeh',
age = 250,
country = 'Finland',
city = 'Helsinki'
) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
}
}
const person1 = new Person() // it will take the default values
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
console.log(person1)
console.log(person2)
```
```sh
Person {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki"}
Person {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Espoo"}
```
### Metodi di Classe
Il costruttore all'interno di una classe è una funzione incorporata che ci permette di creare un progetto per l'oggetto. In una classe possiamo creare metodi di classe. I metodi sono funzioni JavaScript all'interno della classe. Creiamo alcuni metodi della classe.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
console.log(person1.getFullName())
console.log(person2.getFullName())
```
```sh
Asabeneh Yetayeh
test.js:19 Lidiya Tekle
```
### Proprietà con valori iniziali
Quando creiamo una classe per alcune proprietà possiamo avere un valore iniziale. Per esempio, se si sta giocando, il punteggio iniziale sarà zero. Quindi, possiamo avere un punteggio iniziale o un punteggio che è zero. In altri termini, potremmo avere un'abilità iniziale e acquisirla dopo qualche tempo.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
console.log(person1.score)
console.log(person2.score)
console.log(person1.skills)
console.log(person2.skills)
```
```sh
0
0
[]
[]
```
Un metodo può essere un metodo normale, un getter o un setter. Vediamo i metodi getter e setter.
### getter
Il metodo get ci consente di accedere al valore dell'oggetto. Scriviamo un metodo get usando la parola chiave _get_ seguita da una funzione. Invece di accedere alle proprietà direttamente dall'oggetto, usiamo getter per ottenere il valore. Vedere l'esempio seguente
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getScore() {
return this.score
}
get getSkills() {
return this.skills
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
console.log(person1.getScore) // We do not need parenthesis to call a getter method
console.log(person2.getScore)
console.log(person1.getSkills)
console.log(person2.getSkills)
```
```sh
0
0
[]
[]
```
### setter
Il metodo setter ci consente di modificare il valore di alcune proprietà. Scriviamo un metodo setter usando la parola chiave _set_ seguita da una funzione. Si veda l'esempio qui sotto.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getScore() {
return this.score
}
get getSkills() {
return this.skills
}
set setScore(score) {
this.score += score
}
set setSkill(skill) {
this.skills.push(skill)
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
person1.setScore = 1
person1.setSkill = 'HTML'
person1.setSkill = 'CSS'
person1.setSkill = 'JavaScript'
person2.setScore = 1
person2.setSkill = 'Planning'
person2.setSkill = 'Managing'
person2.setSkill = 'Organizing'
console.log(person1.score)
console.log(person2.score)
console.log(person1.skills)
console.log(person2.skills)
```
```sh
1
1
["HTML", "CSS", "JavaScript"]
["Planning", "Managing", "Organizing"]
```
Non lasciatevi ingannare dalla differenza tra un metodo regolare e un getter. Se sapete come creare un metodo regolare, siete a posto. Aggiungiamo un metodo regolare chiamato getPersonInfo nella classe Person.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getScore() {
return this.score
}
get getSkills() {
return this.skills
}
set setScore(score) {
this.score += score
}
set setSkill(skill) {
this.skills.push(skill)
}
getPersonInfo() {
let fullName = this.getFullName()
let skills =
this.skills.length > 0 &&
this.skills.slice(0, this.skills.length - 1).join(', ') +
` and ${this.skills[this.skills.length - 1]}`
let formattedSkills = skills ? `He knows ${skills}` : ''
let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`
return info
}
}
const person1 = new Person('Asabeneh', 'Yetayeh', 250, 'Finland', 'Helsinki')
const person2 = new Person('Lidiya', 'Tekle', 28, 'Finland', 'Espoo')
const person3 = new Person('John', 'Doe', 50, 'Mars', 'Mars city')
person1.setScore = 1
person1.setSkill = 'HTML'
person1.setSkill = 'CSS'
person1.setSkill = 'JavaScript'
person2.setScore = 1
person2.setSkill = 'Planning'
person2.setSkill = 'Managing'
person2.setSkill = 'Organizing'
console.log(person1.getScore)
console.log(person2.getScore)
console.log(person1.getSkills)
console.log(person2.getSkills)
console.log(person3.getSkills)
console.log(person1.getPersonInfo())
console.log(person2.getPersonInfo())
console.log(person3.getPersonInfo())
```
```sh
1
1
["HTML", "CSS", "JavaScript"]
["Planning", "Managing", "Organizing"]
[]
Asabeneh Yetayeh is 250. He lives Helsinki, Finland. He knows HTML, CSS and JavaScript
Lidiya Tekle is 28. He lives Espoo, Finland. He knows Planning, Managing and Organizing
John Doe is 50. He lives Mars city, Mars.
```
### Metodo Statico
La parola chiave static definisce un metodo statico per una classe. I metodi statici non vengono richiamati sulle istanze della classe. Vengono invece richiamati sulla classe stessa. Si tratta spesso di funzioni di utilità, come quelle per creare o clonare oggetti. Un esempio di metodo statico è _Date.now()_. Il metodo _now_ viene richiamato direttamente dalla classe.
```js
class Person {
constructor(firstName, lastName, age, country, city) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.country = country
this.city = city
this.score = 0
this.skills = []
}
getFullName() {
const fullName = this.firstName + ' ' + this.lastName
return fullName
}
get getScore() {
return this.score
}
get getSkills() {
return this.skills
}
set setScore(score) {
this.score += score
}
set setSkill(skill) {
this.skills.push(skill)
}
getPersonInfo() {
let fullName = this.getFullName()
let skills =
this.skills.length > 0 &&
this.skills.slice(0, this.skills.length - 1).join(', ') +
` and ${this.skills[this.skills.length - 1]}`
let formattedSkills = skills ? `He knows ${skills}` : ''
let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`
return info
}
static favoriteSkill() {
const skills = ['HTML', 'CSS', 'JS', 'React', 'Python', 'Node']
const index = Math.floor(Math.random() * skills.length)
return skills[index]
}
static showDateTime() {
let now = new Date()
let year = now.getFullYear()
let month = now.getMonth() + 1
let date = now.getDate()
let hours = now.getHours()
let minutes = now.getMinutes()
if (hours < 10) {
hours = '0' + hours
}
if (minutes < 10) {
minutes = '0' + minutes
}
let dateMonthYear = date + '.' + month + '.' + year
let time = hours + ':' + minutes
let fullTime = dateMonthYear + ' ' + time
return fullTime
}
}
console.log(Person.favoriteSkill())
console.log(Person.showDateTime())
```
```sh
Node
15.1.2020 23:56
```
The static methods are methods which can be used as utility functions.
## Inheritance (Ereditarietà)
Utilizzando l'ereditarietà, possiamo accedere a tutte le proprietà e ai metodi della classe madre. Questo riduce la ripetizione del codice. Se ricordate, abbiamo una classe genitore Persona e da questa creeremo dei figli. I nostri figli potrebbero essere studenti, insegnanti, ecc.
```js
// syntax
class ChildClassName extends {
// code goes here
}
```
Creiamo una classe figlio Student dalla classe genitore Person.
```js
class Student extends Person {
saySomething() {
console.log('I am a child of the person class')
}
}
const s1 = new Student('Asabeneh', 'Yetayeh', 'Finland', 250, 'Helsinki')
console.log(s1)
console.log(s1.saySomething())
console.log(s1.getFullName())
console.log(s1.getPersonInfo())
```
```sh
Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …}
I am a child of the person class
Asabeneh Yetayeh
Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …}
Asabeneh Yetayeh is Finland. He lives Helsinki, 250.
```
### Override dei metodi
Come si può vedere, riusciamo ad accedere a tutti i metodi della classe Person e li utilizziamo nella classe figlio Student. Possiamo personalizzare i metodi dei genitori e aggiungere proprietà aggiuntive a una classe figlio. Se vogliamo personalizzare i metodi e aggiungere proprietà aggiuntive, dobbiamo utilizzare la funzione costruttore anche per la classe figlio. All'interno della funzione costruttore chiamiamo la funzione super() per accedere a tutte le proprietà della classe genitore. La classe Person non aveva il genere, ma ora diamo la proprietà gender alla classe figlio, Student. Se lo stesso nome del metodo viene utilizzato nella classe figlio, il metodo genitore verrà sovrascritto.
```js
class Student extends Person {
constructor(firstName, lastName, age, country, city, gender) {
super(firstName, lastName, age, country, city)
this.gender = gender
}
saySomething() {
console.log('I am a child of the person class')
}
getPersonInfo() {
let fullName = this.getFullName()
let skills =
this.skills.length > 0 &&
this.skills.slice(0, this.skills.length - 1).join(', ') +
` and ${this.skills[this.skills.length - 1]}`
let formattedSkills = skills ? `He knows ${skills}` : ''
let pronoun = this.gender == 'Male' ? 'He' : 'She'
let info = `${fullName} is ${this.age}. ${pronoun} lives in ${this.city}, ${this.country}. ${formattedSkills}`
return info
}
}
const s1 = new Student(
'Asabeneh',
'Yetayeh',
250,
'Finland',
'Helsinki',
'Male'
)
const s2 = new Student('Lidiya', 'Tekle', 28, 'Finland', 'Helsinki', 'Female')
s1.setScore = 1
s1.setSkill = 'HTML'
s1.setSkill = 'CSS'
s1.setSkill = 'JavaScript'
s2.setScore = 1
s2.setSkill = 'Planning'
s2.setSkill = 'Managing'
s2.setSkill = 'Organizing'
console.log(s1)
console.log(s1.saySomething())
console.log(s1.getFullName())
console.log(s1.getPersonInfo())
console.log(s2.saySomething())
console.log(s2.getFullName())
console.log(s2.getPersonInfo())
```
```sh
Student {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki", …}
Student {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Helsinki", …}
I am a child of the person class
Asabeneh Yetayeh
Student {firstName: "Asabeneh", lastName: "Yetayeh", age: 250, country: "Finland", city: "Helsinki", …}
Asabeneh Yetayeh is 250. He lives in Helsinki, Finland. He knows HTML, CSS and JavaScript
I am a child of the person class
Lidiya Tekle
Student {firstName: "Lidiya", lastName: "Tekle", age: 28, country: "Finland", city: "Helsinki", …}
Lidiya Tekle is 28. She lives in Helsinki, Finland. He knows Planning, Managing and Organizing
```
Ora, il metodo getPersonInfo è stato sovrascritto e identifica se la persona è maschio o femmina.
🌕 Stai eccellendo. Ora conosci la classe e hai il potere di trasformare tutto in un oggetto. Hai raggiunto la metà della tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## Esercizi
### Esercizi Livello 1
1. Creare una classe Animale. La classe avrà le proprietà nome, età, colore, zampe e creerà diversi metodi.
2. Creare una classe figlio Cane e Gatto dalla classe Animale.
### Esercizi Livello 2
1. Sovrascrivere il metodo creato nella classe Animale
### Esercizi Livello 3
1. Proviamo a sviluppare un programma che calcoli la misura della tendenza centrale di un campione (media, mediana, modalità) e la misura della variabilità (intervallo, varianza, deviazione standard). Oltre a queste misure, trova il minimo, il massimo, il numero, il percentile e la distribuzione di frequenza del campione. È possibile creare una classe chiamata Statistica e creare tutte le funzioni che eseguono calcoli statistici come metodi per la classe Statistica. Verificate l'output qui sotto.
```JS
ages = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
console.log('Count:', statistics.count()) // 25
console.log('Sum: ', statistics.sum()) // 744
console.log('Min: ', statistics.min()) // 24
console.log('Max: ', statistics.max()) // 38
console.log('Range: ', statistics.range() // 14
console.log('Mean: ', statistics.mean()) // 30
console.log('Median: ',statistics.median()) // 29
console.log('Mode: ', statistics.mode()) // {'mode': 26, 'count': 5}
console.log('Variance: ',statistics.var()) // 17.5
console.log('Standard Deviation: ', statistics.std()) // 4.2
console.log('Variance: ',statistics.var()) // 17.5
console.log('Frequency Distribution: ',statistics.freqDist()) // [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
```sh
// you output should look like this
console.log(statistics.describe())
Count: 25
Sum: 744
Min: 24
Max: 38
Range: 14
Mean: 30
Median: 29
Mode: (26, 5)
Variance: 17.5
Standard Deviation: 4.2
Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
1. Creare una classe chiamata PersonAccount. Ha le proprietà nome, cognome, reddito, spese e i metodi totalIncome, totalExpense, accountInfo, addIncome, addExpense e accountBalance. Le entrate sono un insieme di entrate e la loro descrizione e le spese sono anch'esse un insieme di spese e la loro descrizione.
🎉 CONGRATULAZIONI ! 🎉
[<< Day 14](../14_Day_Error_handling/14_day_error_handling.md) | [Day 16>>](../16_Day_JSON/16_day_json.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)
![Thirty Days Of JavaScript](../../images/banners/day_1_16.png)
- [Day 16](#day-16)
- [JSON](#json)
- [Convertire un JSON in Oggetto JavaScript ](#converting-json-to-javascript-object)
- [JSON.parse()](#jsonparse)
- [Usare una funzione reviver con JSON.parse()](#using-a-reviver-function-with-jsonparse)
- [Convertire un Oggetto in JSON](#converting-object-to-json)
- [Usare un Filter Array con 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 è l'acronimo di JavaScript Object Notation. La sintassi JSON deriva dalla sintassi della notazione degli oggetti JavaScript, ma il formato JSON è solo testo o stringa. JSON è un formato di dati leggero per la memorizzazione e il trasporto. JSON viene utilizzato soprattutto quando i dati vengono inviati da un server a un client. JSON è un'alternativa più facile da usare rispetto a 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"
}
]
}
```
L'esempio JSON di cui sopra non è molto diverso da un normale oggetto. Allora, qual è la differenza? La differenza sta nel fatto che la chiave di un oggetto JSON deve essere con doppi apici o deve essere una stringa. Gli oggetti JavaScript e JSON sono molto simili, tanto che possiamo cambiare JSON in oggetto e oggetto in JSON.
Vediamo in dettaglio l'esempio precedente, che inizia con una parentesi graffa. All'interno della parentesi graffa, c'è la chiave "utenti" che ha un array di valori. All'interno dell'array abbiamo diversi oggetti e ogni oggetto ha delle chiavi, ogni chiave deve avere i doppi apici. Per esempio, usiamo "firstNaMe" invece del semplice firstName, ma negli oggetti usiamo chiavi senza doppi apici. Questa è la differenza principale tra un oggetto e un JSON. Vediamo altri esempi di 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
}
}
```
### Convertire un JSON in Oggetto JavaScript
In genere si recuperano dati JSON dalla risposta HTTP o da un file, ma è possibile memorizzare il JSON come stringa e, a scopo dimostrativo, trasformarlo in oggetto. In JavaScript la parola chiave _JSON_ ha i metodi _parse()_ e _stringify()_. Quando vogliamo cambiare il JSON in un oggetto, lo analizziamo usando _JSON.parse()_. Quando vogliamo cambiare l'oggetto in JSON, usiamo _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)
```
### Usare una funzione reviver con JSON.parse()
Per utilizzare la funzione reviver come formattatore, si inseriscono le chiavi con cui si vuole formattare i valori di nome e cognome. Supponiamo di essere interessati a formattare il nome e il cognome dei dati JSON.
```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)
```
Il metodo _JSON.parse()_ è molto comodo da usare. Non è necessario passare un parametro opzionale, basta usarlo con il parametro richiesto e si otterrà molto.
### Convertire un Oggetto in JSON
Quando vogliamo cambiare l'oggetto in JSON, usiamo _JSON.stringify()_. Il metodo stringify accetta un parametro obbligatorio e due parametri opzionali. Il sostituente è usato come filtro e lo spazio è una rientranza. Se non si vuole filtrare nessuna delle chiavi dell'oggetto, si può passare semplicemente undefined.
```js
JSON.stringify(obj, replacer, space)
// json or text , the data
// reviver is an optional callback function
```
Convertiamo il seguente oggetto in una stringa. Per prima cosa manteniamo tutte le chiavi e manteniamo un'indentazione di 4 spazi.
```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
}
}
```
### Usare un Filter Array con JSON.stringify
Ora, usiamo il replacer come filtro. L'oggetto utente ha un lungo elenco di chiavi, ma a noi interessano solo alcune di esse. Mettiamo le chiavi che vogliamo conservare in un array, come mostrato nell'esempio, e lo usiamo al posto del 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
}
```
🌕 Sei straordinario. Ora conosci un formato di dati leggero che puoi usare per memorizzare i dati o per inviarli a un server HTTP. Sei a 16 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## 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. Cambiare l'array di competenze in JSON usando JSON.stringify()
1. Stringere la variabile età
1. Stringere la variabile isMarried
1. Stringere l'oggetto studente
### Esercizi Livello 2
1. Stringificare l'oggetto studenti con le sole proprietà firstName, lastName e skills
### Esercizi Livello 3
1. Analizzare il JSON *txt* in un oggetto.
2. Trovare l'utente che ha molte competenze dalla variabile memorizzata 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,233 @@
<div align="center">
<h1> 30 Days Of JavaScript: Web Storages</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 16](../16_Day_JSON/16_day_json.md) | [Day 18 >>](../18_Day_Promises/18_day_promises.md)
![Thirty Days Of JavaScript](../../images/banners/day_1_17.png)
- [Day 17](#day-17)
- [HTML5 Web Storage](#html5-web-storage)
- [sessionStorage](#sessionstorage)
- [localStorage](#localstorage)
- [Casi d'uso per il Web Storage](#use-case-of-web-storages)
- [Oggetti HTML5 Web Storage](#html5-web-storage-objects)
- [Impostare elementi nel localStorage](#setting-item-to-the-localstorage)
- [Ottenere elementi dal localStorage](#getting-item-from-localstorage)
- [Svuotare il localStorage](#clearing-the-localstorage)
- [Esercizi](#exercises)
- [Esercizi: Livello 1](#exercises-level-1)
- [Esercizi: Livello 2](#exercises-level-2)
- [Esercizi: Livello 3](#exercises-level-3)
# Day 17
## HTML5 Web Storage
Web Storage (sessionStorage e localStorage) è una nuova API HTML5 che offre importanti vantaggi rispetto ai cookie tradizionali. Prima di HTML5, i dati delle applicazioni dovevano essere memorizzati nei cookie, inclusi in ogni richiesta del server. La memorizzazione sul Web è più sicura e grandi quantità di dati possono essere memorizzate localmente, senza influire sulle prestazioni del sito web. Il limite di memorizzazione dei dati dei cookie in molti browser web è di circa 4 KB per cookie. We Storages può memorizzare dati molto più grandi (almeno 5 MB) e non vengono mai trasferiti al server. Tutti i siti della stessa o di una stessa origine possono memorizzare e accedere agli stessi dati.
È possibile accedere ai dati memorizzati utilizzando JavaScript, che consente di sfruttare lo scripting lato client per fare molte cose che tradizionalmente richiedevano la programmazione lato server e i database relazionali. Esistono due oggetti Web Storage:
- sessionStorage
- localStorage
localStorage è simile a sessionStorage, tranne per il fatto che mentre i dati memorizzati in localStorage non hanno scadenza, i dati memorizzati in sessionStorage vengono cancellati quando la sessione della pagina termina, cioè quando la pagina viene chiusa.
Va notato che i dati memorizzati in localStorage o in sessionStorage sono specifici del protocollo della pagina.
Le chiavi e i valori sono sempre stringhe (si noti che, come per gli oggetti, le chiavi intere saranno automaticamente convertite in stringhe).
![web_storage](../../images/web_storage.png)
### sessionStorage
sessionStorage è disponibile solo all'interno della sessione della scheda o della finestra del browser. È progettato per memorizzare i dati in una singola sessione della pagina web. Ciò significa che se la finestra viene chiusa, i dati della sessione vengono rimossi. Poiché sessionStorage e localStorage hanno metodi simili, ci concentreremo solo su localStorage.
### localStorage
HTML5 localStorage è il para dell'API di archiviazione web che viene utilizzato per memorizzare i dati sul browser senza scadenza. I dati saranno disponibili sul browser anche dopo la sua chiusura. localStorage viene mantenuto anche tra le sessioni del browser. Ciò significa che i dati sono ancora disponibili quando il browser viene chiuso e riaperto e anche istantaneamente tra le schede e le finestre.
I dati di Web Storage, in entrambi i casi, non sono disponibili tra i diversi browser. Ad esempio, gli oggetti di memorizzazione creati in Firefox non sono accessibili in Internet Explorer, esattamente come i cookie. Esistono cinque metodi per lavorare sull'archiviazione locale:
_setItem(), getItem(), removeItem(), clear(), key()_
### Casi d'uso per il Web Storage
Alcuni casi d'uso degli archivi web sono
- memorizzare temporaneamente i dati
- salvare i prodotti che l'utente inserisce nel suo carrello della spesa
- i dati possono essere resi disponibili tra le richieste di pagina, tra più schede del browser e anche tra le sessioni del browser utilizzando localStorage
- possono essere utilizzati completamente offline utilizzando localStorage.
- Il Web Storage può essere un grande vantaggio in termini di prestazioni quando alcuni dati statici vengono memorizzati sul client per ridurre al minimo il numero di richieste successive. Anche le immagini possono essere memorizzate in stringhe utilizzando la codifica Base64.
- può essere usato per il metodo di autenticazione dell'utente
Per gli esempi sopra citati, ha senso usare localStorage. Ci si potrebbe chiedere, allora, quando si dovrebbe usare sessionStorage.
Nel caso in cui si voglia sbarazzarsi dei dati non appena la finestra viene chiusa. Oppure, se non si vuole che l'applicazione interferisca con la stessa applicazione aperta in un'altra finestra. Questi scenari sono meglio serviti con sessionStorage.
Vediamo ora come utilizzare queste API di Web Storage.
## Oggetti HTML5 Web Storage
Il web storage HTML fornisce due oggetti per la memorizzazione dei dati sul client:
- window.localStorage - memorizza i dati senza data di scadenza
- window.sessionStorage - memorizza i dati per una sessione (i dati vengono persi quando la scheda del browser viene chiusa)La maggior parte dei browser moderni supporta Web Storage, tuttavia è bene verificare il supporto del browser per localStorage e sessionStorage. Vediamo i metodi disponibili per gli oggetti Web Storage.
Oggetti Web Storage:
- _localStorage_ - per visualizzare l'oggetto localStorage
- _localStorage.clear()_ - per rimuovere tutto ciò che è presente nel localStorage
- _localStorage.setItem()_ - per memorizzare i dati nel localStorage. Richiede i parametri chiave e valore.
- _localStorage.getItem()_ - per visualizzare i dati memorizzati nel localStorage. Richiede una chiave come parametro.
- _localStorage.removeItem()_ - per rimuovere un elemento memorizzato dal localStorage. Richiede la chiave come parametro.
- _localStorage.key()_ - per visualizzare un dato memorizzato in un localStorage. Richiede l'indice come parametro.
![local_storage](../../images/local_storage.png)
### Impostare elementi nel localStorage
Quando si impostano i dati da memorizzare in un localStorage, questi vengono memorizzati come stringa. Se stiamo memorizzando un array o un oggetto, dovremmo prima stringare per mantenere il formato, a meno che non si perda la struttura dell'array o dell'oggetto dei dati originali.
I dati vengono memorizzati nel localStorage utilizzando il metodo _localStorage.setItem_.
```js
//syntax
localStorage.setItem('key', 'value')
```
- Memorizzazione di stringhe in un localStorage
```js
localStorage.setItem('firstName', 'Asabeneh') // since the value is string we do not stringify it
console.log(localStorage)
```
```sh
Storage {firstName: 'Asabeneh', length: 1}
```
- Storing number in a local storage
```js
localStorage.setItem('age', 200)
console.log(localStorage)
```
```sh
Storage {age: '200', firstName: 'Asabeneh', length: 2}
```
- Memorizzazione di un array in un localStorage. Se si memorizza un array, un oggetto o un array di oggetti, occorre prima stringere l'oggetto. Vedere l'esempio seguente.
```js
const skills = ['HTML', 'CSS', 'JS', 'React']
//Skills array has to be stringified first to keep the format.
const skillsJSON = JSON.stringify(skills, undefined, 4)
localStorage.setItem('skills', skillsJSON)
console.log(localStorage)
```
```sh
Storage {age: '200', firstName: 'Asabeneh', skills: 'HTML,CSS,JS,React', length: 3}
```
```js
let skills = [
{ tech: 'HTML', level: 10 },
{ tech: 'CSS', level: 9 },
{ tech: 'JS', level: 8 },
{ tech: 'React', level: 9 },
{ tech: 'Redux', level: 10 },
{ tech: 'Node', level: 8 },
{ tech: 'MongoDB', level: 8 }
]
let skillJSON = JSON.stringify(skills)
localStorage.setItem('skills', skillJSON)
```
- Memorizzazione di un oggetto in un localStorage. Prima di memorizzare gli oggetti in un localStorage, l'oggetto deve essere stringato.
```js
const user = {
firstName: 'Asabeneh',
age: 250,
skills: ['HTML', 'CSS', 'JS', 'React']
}
const userText = JSON.stringify(user, undefined, 4)
localStorage.setItem('user', userText)
```
### Ottenere elementi dal localStorage
Si ottengono i dati dalla memoria locale con il metodo _localStorage.getItem()_.
```js
//syntax
localStorage.getItem('key')
```
```js
let firstName = localStorage.getItem('firstName')
let age = localStorage.getItem('age')
let skills = localStorage.getItem('skills')
console.log(firstName, age, skills)
```
```sh
'Asabeneh', '200', '['HTML','CSS','JS','React']'
```
Come si può vedere, l'abilità è in formato stringa. Utilizziamo JSON.parse() per analizzarla in un normale array.
```js
let skills = localStorage.getItem('skills')
let skillsObj = JSON.parse(skills, undefined, 4)
console.log(skillsObj)
```
```sh
['HTML','CSS','JS','React']
```
### Svuotare il localStorage
Il metodo clear cancella tutto ciò che è memorizzato nella memoria locale.
```js
localStorage.clear()
```
🌕 Ora conosci un Web Storages e sai come memorizzare piccoli dati sui browser dei client. Sei a 17 passi dalla tua strada verso la grandezza. Ora fai qualche esercizio per il tuo cervello e per i muscoli.
## Esercizi
### Esercizi: Livello 1
1. Memorizzare nome, cognome, età, paese e città nel browser localStorage.
### Esercizi: Livello 2
1. Creare un oggetto studente. L'oggetto studente avrà nome, cognome, età, competenze, nazione, chiavi di iscrizione e valori per le chiavi. Memorizzare l'oggetto studente nel localStorage del browser.
### Esercizi: Livello 3
1. Creare un oggetto chiamato personAccount. Ha le proprietà nome, cognome, reddito, spese e i metodi totalIncome, totalExpense, accountInfo, addIncome, addExpense e accountBalance. Le entrate sono un insieme di entrate e la loro descrizione e le spese sono anch'esse un insieme di spese e la loro descrizione.
🎉 CONGRATULAZIONI ! 🎉
[<< Day 16](../16_Day_JSON/16_day_json.md) | [Day 18 >>](../18_Day_Promises/18_day_promises.md)

@ -0,0 +1,273 @@
<div align="center">
<h1> 30 Days Of JavaScript: Promises</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 17](../17_Day_Web_storages/17_day_web_storages.md) | [Day 19>>](../19_Day_Closures/19_day_closures.md)
![Thirty Days Of JavaScript](../../images/banners/day_1_18.png)
- [Day 18](#day-18)
- [Promise](#promise)
- [Callbacks](#callbacks)
- [Costruttore Promise](#promise-constructor)
- [Fetch API](#fetch-api)
- [Async and Await](#async-and-await)
- [Esercizi](#exercises)
- [Esercizi: Livello 1](#exercises-level-1)
- [Esercizi: Livello 2](#exercises-level-2)
- [Esercizi: Livello 3](#exercises-level-3)
# Day 18
## Promise
Noi esseri umani facciamo o riceviamo la promessa di svolgere un'attività in un determinato momento. Se manteniamo la promessa, rendiamo felici gli altri, ma se non la manteniamo, possiamo essere scontenti. La promessa in JavaScript ha qualcosa in comune con gli esempi precedenti.
Una promessa è un modo per gestire operazioni asincrone in JavaScript. Permette ai gestori di avere un valore di successo o un motivo di fallimento di un'azione asincrona. Ciò consente ai metodi asincroni di restituire valori come i metodi sincroni: invece di restituire immediatamente il valore finale, il metodo asincrono restituisce una promessa di fornire il valore in un momento futuro.
Una promessa si trova in uno di questi stati:
- pending: stato iniziale, né soddisfatto né rifiutato.
- soddisfatta: significa che l'operazione è stata completata con successo.
- rifiutata: significa che l'operazione è fallita.
Una promessa in sospeso può essere soddisfatta con un valore o rifiutata con un motivo (errore). Quando si verifica una di queste opzioni, vengono richiamati i gestori associati messi in coda dal metodo then di una promessa. (Se la promessa è già stata soddisfatta o rifiutata quando viene collegato un gestore corrispondente, il gestore verrà chiamato, in modo che non ci sia una condizione di gara tra il completamento di un'operazione asincrona e il collegamento dei suoi gestori).
Poiché i metodi Promise.prototype.then() e Promise.prototype.catch() restituiscono promesse, possono essere concatenati.
## Callbacks
Per comprendere bene la promise, dobbiamo prima capire le callback. Vediamo le seguenti callback. Dai seguenti blocchi di codice si noterà la differenza tra callback e promise.
- callback
Vediamo una funzione di callback che può accettare due parametri. Il primo parametro è err e il secondo è result. Se il parametro err è false, non ci sarà alcun errore, altrimenti restituirà un errore.
In questo caso err ha un valore e restituirà il blocco err.
```js
//Callback
const doSomething = callback => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
callback('It did not go well', skills)
}, 2000)
}
const callback = (err, result) => {
if (err) {
return console.log(err)
}
return console.log(result)
}
doSomething(callback)
```
```sh
// after 2 seconds it will print
It did not go well
```
In questo caso l'errore è falso e restituirà il blocco else che è il risultato.
```js
const doSomething = callback => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
callback(false, skills)
}, 2000)
}
doSomething((err, result) => {
if (err) {
return console.log(err)
}
return console.log(result)
})
```
```sh
// after 2 seconds it will print the skills
["HTML", "CSS", "JS"]
```
### Costruttore Promise
Possiamo creare una promessa utilizzando il costruttore Promise. Possiamo creare una nuova promessa usando la parola chiave `new` seguita dalla parola `Promise` e seguita da una parentesi. All'interno della parentesi, prende una funzione `callback`. La funzione di callback della promessa ha due parametri, che sono le funzioni _`resolve`_ e _`reject`_.
```js
// syntax
const promise = new Promise((resolve, reject) => {
resolve('success')
reject('failure')
})
```
```js
// Promise
const doPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
if (skills.length > 0) {
resolve(skills)
} else {
reject('Something wrong has happened')
}
}, 2000)
})
doPromise
.then(result => {
console.log(result)
})
.catch(error => console.log(error))
```
```sh
["HTML", "CSS", "JS"]
```
La promessa di cui sopra è stata risolta con resolve.
Facciamo un altro esempio quando la promessa viene risolta con un rifiuto.
```js
// Promise
const doPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const skills = ['HTML', 'CSS', 'JS']
if (skills.includes('Node')) {
resolve('fullstack developer')
} else {
reject('Something wrong has happened')
}
}, 2000)
})
doPromise
.then(result => {
console.log(result)
})
.catch(error => console.error(error))
```
```sh
Something wrong has happened
```
## Fetch API
L'API Fetch fornisce un'interfaccia per il recupero di risorse (anche attraverso la rete). Sembrerà familiare a chiunque abbia usato XMLHttpRequest, ma la nuova API fornisce un insieme di funzionalità più potenti e flessibili. In questa sfida useremo fetch per richiedere url e APIS. Inoltre, vedremo un caso d'uso dimostrativo delle promesse per accedere alle risorse di rete utilizzando l'API fetch.
```js
const url = 'https://restcountries.com/v2/all' // countries api
fetch(url)
.then(response => response.json()) // accessing the API data as JSON
.then(data => {
// getting the data
console.log(data)
})
.catch(error => console.error(error)) // handling error if something wrong happens
```
## Async and Await
Async e await sono un modo elegante di gestire le promesse. È facile da capire e pulito da scrivere.
```js
const square = async function (n) {
return n * n
}
square(2)
```
```sh
Promise {<resolved>: 4}
```
La parola _async_ davanti a una funzione significa che la funzione restituirà una promessa. La funzione quadrata di cui sopra, invece di un valore, restituisce una promessa.
Come si accede al valore della promessa? Per accedere al valore della promessa, utilizzeremo la parola chiave _await_.
```js
const square = async function (n) {
return n * n
}
const value = await square(2)
console.log(value)
```
```sh
4
```
Ora, come si può vedere dall'esempio precedente, scrivendo async davanti a una funzione si crea una promessa e per ottenere il valore da una promessa si usa await. Async e await vanno insieme, uno non può esistere senza l'altro.
Cerchiamo di recuperare i dati dell'API utilizzando sia il metodo promise che i metodi async e await.
- promise
```js
const url = 'https://restcountries.com/v2/all'
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(error => console.error(error))
```
- async and await
```js
const fetchData = async () => {
try {
const response = await fetch(url)
const countries = await response.json()
console.log(countries)
} catch (err) {
console.error(err)
}
}
console.log('===== async and await')
fetchData()
```
🌕 Sei reale, hai mantenuto la tua promessa e sei arrivato al 18° giorno. Mantieni la tua promessa e affronta la sfida con determinazione. Sei 18 passi avanti verso la tua strada verso la grandezza. Ora fai qualche esercizio per il cervello e i muscoli.
## Esercizi
```js
const countriesAPI = 'https://restcountries.com/v2/all'
const catsAPI = 'https://api.thecatapi.com/v1/breeds'
```
### Esercizi: Livello 1
1. Leggere le API dei paesi utilizzando fetch e stampare il nome del paese, la capitale, le lingue, la popolazione e l'area.
### Esercizi: Livello 2
1. Stampare tutti i nomi dei gatti nella variabile catNames.
### Esercizi: Livello 3
1. Leggere l'api gatti e trovare il peso medio dei gatti in unità metriche.
2. Leggete l'api dei Paesi e trovate i 10 Paesi più grandi.
3. Leggete l'api dei Paesi e contate il numero totale di lingue del mondo usate come ufficiali.
🎉 CONGRATULAZIONI ! 🎉
[<< Day 17](../17_Day_Web_storages/17_day_web_storages.md) | [Day 19>>](../19_Day_Closures/19_day_closures.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)
![Thirty Days Of JavaScript](../../images/banners/day_1_19.png)
- [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 consente di scrivere una funzione all'interno di una funzione esterna. Possiamo scrivere tutte le funzioni interne che vogliamo. Se la funzione interna accede alle variabili della funzione esterna, si parla di chiusura.
```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
```
Vediamo altri esempi di funzioni interne
```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
```
🌕 State facendo progressi. Mantenete lo slancio, continuate a lavorare bene. Ora fate qualche esercizio per il cervello e per i muscoli.
## Esercizi
### Esercizi: Livello 1
1. Creare una chiusura che abbia una funzione interna
### Esercizi: Livello 2
1. Creare una chiusura con tre funzioni interne
### Esercizi: Livello 3
1. Creare una funzione esterna PersonAccount. Ha le variabili interne nome, cognome, reddito e spese. Ha le funzioni interne totalIncome, totalExpense, accountInfo, addIncome, addExpense e accountBalance. Entrate è un insieme di entrate e relativa descrizione e spese è un insieme di spese e relativa descrizione.
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_20.png)
- [Day 20](#day-20)
- [Scrivere codice pulito](#writing-clean-code)
- [Guida allo stile in JavaScript](#javascript-style-guide)
- [Perché abbiamo bisogno di uno stile](#why-we-need-style-guide)
- [Guida allo stile Airbnb](#airbnb-javascript-style-guide)
- [Guida allo stile Standard JavaScript](#standard-javascript-style-guide)
- [Guida allo stile Google](#google-javascript-style-guide)
- [Convenzioni del codice JavaScript](#javascript-coding-conventions)
- [Convenzioni usate in 30DaysOfJavaScript](#conventions-use-in-30daysofjavascript)
- [Variables](#variables)
- [Arrays](#arrays)
- [Functions](#functions)
- [Loops](#loops)
- [Objects](#objects)
- [Conditional](#conditional)
- [Classes](#classes)
# Day 20
## Scrivere codice pulito
### Guida allo stile in JavaScript
Una guida di stile JavaScript è un insieme di standard che indica come il codice JavaScript dovrebbe essere scritto e organizzato. In questa sezione parleremo delle guide JavaScript e di come scrivere un codice pulito.
JavaScript è un linguaggio di programmazione e, come i linguaggi umani, ha una sintassi. La sintassi di JavaScript deve essere scritta seguendo una certa linea guida di stile, per motivi di convinzione e semplicità.
### Perché abbiamo bisogno di uno stile
Avete codificato da soli per tanto tempo, ma ora sembra che dobbiate lavorare in team. Non importa in che modo scriviate il codice, purché funzioni, ma quando lavorate in un team di 10 o 20 o più sviluppatori su un progetto e sullo stesso codice base, il codice sarà disordinato e difficile da gestire se non ci sono linee guida da seguire.
È possibile sviluppare linee guida e convenzioni proprie o adattare linee guida ben sviluppate. Vediamo le linee guida più comuni.
Guida allo stile più comune in JavaScript
- Guida allo stile Airbnb
- Guida allo stile standard di JavaScript
- Guida allo stile Google
#### Guida allo stile Airbnb
Airbnb ha una delle guide di stile JavaScript più popolari su Internet. Copre quasi tutti gli aspetti di JavaScript ed è adottata da molti sviluppatori e aziende. Potete consultare la [Guida allo stile di Airbnb](https://github.com/airbnb/javascript). Vi consiglio di provarla. Il loro stile è molto facile da usare e semplice da capire.
#### Guida allo stile Standard JavaScript
Questa linea guida non è così popolare come Airbnb, ma vale la pena guardarla. Hanno rimosso il punto e virgola nel loro [style guide](https://standardjs.com/).
#### Guida allo stile Google
Non parlo molto delle linee guida di Google e non le ho usate, piuttosto vi suggerisco di dare un'occhiata a questo sito. [link](https://google.github.io/styleguide/jsguide.html).
### Convenzioni del codice JavaScript
Anche in questa sfida abbiamo utilizzato le convenzioni e le guide generali di scrittura di JavaScript. Le convenzioni di codifica sono linee guida di stile per la programmazione sviluppate da un individuo, un team o un'azienda.
Le convenzioni di codifica aiutano a
- scrivere codice pulito
- migliorare la leggibilità del codice
- migliorare la riutilizzabilità e la manutenibilità del codice
Le convenzioni di codifica comprendono
- Regole di denominazione e dichiarazione per le variabili
- Regole di denominazione e dichiarazione per le funzioni
- Regole per l'uso degli spazi bianchi, dell'indentazione e dei commenti.
- Pratiche e principi di programmazione
#### Convenzioni usate in 30DaysOfJavaScript
In questa sfida abbiamo seguito le normali convenzioni di JavaScript, ma ho aggiunto anche le mie preferenze di scrittura.
- Abbiamo usato il camelCase per le variabili e le funzioni.
- Tutti i nomi delle variabili iniziano con una lettera.
- Abbiamo scelto di usare *const* per costanti, array, oggetti e funzioni. Al posto delle doppie virgolette, abbiamo scelto di usare le virgolette singole o il backtick. Le virgolette singole stanno diventando di moda.
- Abbiamo anche eliminato i punti e virgola dal nostro codice, ma è una questione di preferenze personali.
- Spazio intorno agli operatori aritmetici, agli operatori di assegnazione e dopo la virgola.
- Freccia di funzione invece di dichiarazione di funzione
- Ritorno esplicito invece di ritorno implicito se la funzione è one liner
- Nessuna virgola nell'ultimo valore di un oggetto.
- Preferiamo questi +=, -=, *= /=, **= invece della versione più lunga
- Quando si usa console.log() è bene stampare con una stringa di tag per identificare da dove proviene la console
#### Variables
```js
let firstName = 'Asabeneh'
let lastName = 'Yetayeh'
let country = 'Finland'
let city = 'Helsinki'
const PI = Math.PI
const gravity = 9.81
```
#### Arrays
Abbiamo scelto di rendere i nomi degli array plurali
- 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
Ormai conoscete bene la dichiarazione di funzione, la funzione espressione, la funzione freccia e la funzione anonima. In questa sfida tendiamo a usare la funzione freccia invece di altre funzioni. La funzione freccia non sostituisce le altre funzioni. Inoltre, le funzioni freccia e le dichiarazioni di funzione non sono esattamente la stessa cosa. È quindi necessario sapere quando usarle e quando no. Tratterò la differenza in dettaglio in altre sezioni. Utilizzeremo il ritorno esplicito al posto di quello implicito se la funzione è una sola riga.
```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
}
```
Il metodo `new Dat().toLocaleString()` può essere utilizzato anche per visualizzare l'ora della data corrente. I metodi `toLocaleString()` accettano diversi argomenti. Per saperne di più sulla data e sull'ora, consultare questo documento [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString).
#### Loops
In questa sfida copriamo molti tipi di loop. I normali cicli for, while, do while, for of, forEach e for in.
Vediamo come utilizzarli:
```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
Dichiariamo gli oggetti letterali con *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
Nelle sfide precedenti abbiamo parlato di operatori if, if else, if else, switch e ternari.
```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
Dichiariamo la classe con CamelCase, che inizia con la lettera maiuscola.
```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
}
}
```
Qualunque sia la guida di stile che seguite, siate coerenti. Seguite alcuni paradigmi di programmazione e modelli di progettazione. Ricordate che se non scrivete il codice in un certo ordine o modo, sarà difficile leggerlo. Quindi, fate un favore a voi stessi o a chi leggerà il vostro codice scrivendo codice leggibile.
🌕 Sei ordinato. Ora, sapete come scrivere codice pulito, quindi chiunque conosca la lingua inglese può capire il tuo codice. Sei sempre in progresso e sei a 20 passi verso la grandezza.
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_21.png)
- [Day 21](#day-21)
- [Document Object Model (DOM) - Day 1](#document-object-model-dom---day-1)
- [Ottenere un Elemento](#getting-element)
- [Ottenere un Elemento tramite nome tag](#getting-elements-by-tag-name)
- [Ottenere un Elemento tramite nome classe](#getting-elements-by-class-name)
- [Ottenere un Elemento tramite nome id](#getting-an-element-by-id)
- [Ottenere un Elemento tramite i metodi querySelector](#getting-elements-by-using-queryselector-methods)
- [Aggiungere attributi](#adding-attribute)
- [Aggiungere attributi usando setAttribute](#adding-attribute-using-setattribute)
- [Aggiungere attributi senza usare setAttribute](#adding-attribute-without-setattribute)
- [Aggiungere attributi usando classList](#adding-class-using-classlist)
- [Rimuovere una classe usando remove](#removing-class-using-remove)
- [Aggiungere Testo ad un elemento HTML](#adding-text-to-html-element)
- [Aggiungere Testo usando textContent](#adding-text-content-using-textcontent)
- [Aggiungere test usando innerHTML](#adding-text-content-using-innerhtml)
- [Text Content](#text-content)
- [Inner HTML](#inner-html)
- [Aggiungere uno stile](#adding-style)
- [Aggiungere un colore](#adding-style-color)
- [Aggiungere un colore di background](#adding-style-background-color)
- [Definire una dimensione del testo](#adding-style-font-size)
- [Esercizi](#exercises)
- [EsercizioLivello 1](#exercise-level-1)
- [EsercizioLivello 2](#exercise-level-2)
- [EsercizioLivello 3](#exercise-level-3)
- [DOM: Mini project 1](#dom-mini-project-1)
# Day 21
## Document Object Model (DOM) - Day 1
Il documento HTML è strutturato come un oggetto JavaScript. Ogni elemento HTML ha diverse proprietà che possono aiutare a manipolarlo. È possibile ottenere, creare, aggiungere o rimuovere elementi HTML utilizzando JavaScript. Verificate gli esempi riportati di seguito. La selezione di un elemento HTML tramite JavaScript è simile alla selezione tramite CSS. Per selezionare un elemento HTML, si utilizza il nome del tag, l'id, il nome della classe o altri attributi.
### Ottenere un Elemento
Possiamo accedere a elementi o elementi già creati utilizzando JavaScript. Per accedere agli elementi o ottenerli utilizziamo diversi metodi. Il codice sottostante ha quattro elementi _h1_. Vediamo i diversi metodi per accedere agli elementi _h1_.
```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>
```
#### Ottenere un Elemento tramite nome tag
**_getElementsByTagName()_**:prende un nome di tag come parametro stringa e questo metodo restituisce un oggetto HTMLCollection. Una HTMLCollection è un oggetto simile a un array di elementi HTML. La proprietà length fornisce la dimensione dell'insieme. Ogni volta che si utilizza questo metodo, si accede ai singoli elementi utilizzando l'indice o dopo aver eseguito un ciclo su ogni singolo elemento. Un HTMLCollection non supporta tutti i metodi degli array, quindi dovremmo usare il normale ciclo for invece di 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
}
```
#### Ottenere un Elemento tramite nome classe
Il metodo **_getElementsByClassName()_** restituisce un oggetto HTMLCollection. Una HTMLCollection è un elenco di elementi HTML simile a un array. La proprietà length fornisce la dimensione dell'insieme. È possibile scorrere tutti gli elementi di HTMLCollection. Vedere l'esempio seguente
```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
}
```
#### Ottenere un Elemento tramite nome id
**_getElementsById()_** si rivolge a un singolo elemento HTML. Si passa l'id senza # come argomento.
```js
//syntax
document.getElementById('id')
```
```js
let firstTitle = document.getElementById('first-title')
console.log(firstTitle) // <h1>First Title</h1>
```
#### Ottenere un Elemento tramite i metodi querySelector
Il metodo _document.querySelector_ può selezionare un elemento HTML o elementi HTML per nome di tag, id o classe.
**_querySelector_**: può essere usato per selezionare un elemento HTML in base al suo nome di tag, id o classe. Se viene utilizzato il nome del tag, viene selezionato solo il primo elemento.
```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_**: può essere usato per selezionare elementi html in base al nome del tag o della classe. Restituisce un nodeList, che è un oggetto simile a un array che supporta i metodi degli array. Si può usare **_for loop_** o **_forEach_** per scorrere ogni elemento dell'elenco di nodi.
```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
```
### Aggiungere attributi
Nel tag di apertura dell'HTML viene aggiunto un attributo che fornisce informazioni aggiuntive sull'elemento. Attributi HTML comuni: id, class, src, style, href, disabled, title, alt. Aggiungiamo id e class per il quarto titolo.
```js
const titles = document.querySelectorAll('h1')
titles[3].className = 'title'
titles[3].id = 'fourth-title'
```
#### Aggiungere attributi usando setAttribute
Il metodo **_setAttribute()_** imposta qualsiasi attributo html. Richiede due parametri: il tipo di attributo e il nome dell'attributo.
Aggiungiamo gli attributi class e id per il quarto titolo.
```js
const titles = document.querySelectorAll('h1')
titles[3].setAttribute('class', 'title')
titles[3].setAttribute('id', 'fourth-title')
```
#### Aggiungere attributi senza usare setAttribute
Possiamo usare il normale metodo di impostazione degli oggetti per impostare un attributo, ma questo non può funzionare per tutti gli elementi. Alcuni attributi sono proprietà degli oggetti DOM e possono essere impostati direttamente. Ad esempio, id e class
```js
//another way to setting an attribute
titles[3].className = 'title'
titles[3].id = 'fourth-title'
```
#### Aggiungere attributi usando classList
Il metodo dell'elenco di classi è un buon metodo per aggiungere classi supplementari. Non sovrascrive la classe originale, se esiste, ma aggiunge una classe aggiuntiva per l'elemento.
```js
//another way to setting an attribute: append the class, doesn't over ride
titles[3].classList.add('title', 'header-title')
```
#### Rimuovere una classe usando remove
Analogamente all'aggiunta, possiamo anche rimuovere una classe da un elemento. Possiamo rimuovere una classe specifica da un elemento.
```js
//another way to setting an attribute: append the class, doesn't over ride
titles[3].classList.remove('title', 'header-title')
```
### Aggiungere Testo ad un elemento HTML
Un HTML è un blocco composto da un tag di apertura, un tag di chiusura e un contenuto testuale. Possiamo aggiungere un contenuto testuale utilizzando la proprietà _textContent_ o \*innerHTML.
#### Aggiungere Testo usando textContent
La proprietà _textContent_ viene utilizzata per aggiungere testo a un elemento HTML.
```js
const titles = document.querySelectorAll('h1')
titles[3].textContent = 'Fourth Title'
```
#### Aggiungere test usando innerHTML
Molte persone si confondono tra _textContent_ e _innerHTML_. _textContent_ ha lo scopo di aggiungere testo a un elemento HTML, mentre innerHTML può aggiungere uno o più elementi di testo o HTML come figli.
##### Text Content
Assegniamo la proprietà dell'oggetto HTML *textContent* a un testo
```js
const titles = document.querySelectorAll('h1')
titles[3].textContent = 'Fourth Title'
```
##### Inner HTML
Utilizziamo la proprietà innerHTML quando vogliamo sostituire o aggiungere un contenuto completamente nuovo a un elemento genitore.
Il valore assegnato sarà una stringa di elementi HTML.
```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>
```
La proprietà innerHTML può consentire anche di rimuovere tutti i figli di un elemento genitore. Invece di usare removeChild(), raccomanderei il metodo seguente.
```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>
```
### Aggiungere uno stile
#### Aggiungere un colore
Aggiungiamo un po' di stile ai nostri titoli. Se l'elemento ha un indice pari, gli diamo il colore verde, altrimenti il rosso.
```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'
}
})
```
#### Aggiungere un colore di background
Aggiungiamo un po' di stile ai nostri titoli. Se l'elemento ha un indice pari, gli diamo il colore verde, altrimenti il rosso.
```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'
}
})
```
#### Definire una dimensione del testo
Aggiungiamo un po' di stile ai nostri titoli. Se l'elemento ha un indice pari, gli diamo 20px, altrimenti 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'
}
})
```
Come si è notato, le proprietà dei css quando vengono utilizzate in JavaScript saranno in camelCase. Le seguenti proprietà CSS cambiano da background-color a backgroundColor, da font-size a fontSize, da font-family a fontFamily, da margin-bottom a marginBottom.
---
🌕 Ora sei carico di un superpotere, hai completato la parte più importante e impegnativa della sfida e in generale di JavaScript. Hai imparato il DOM e ora hai la capacità di costruire e sviluppare applicazioni. Ora fai qualche esercizio per il cervello e per i muscoli.
## Esercizi
### EsercizioLivello 1
1. Creare un file index.html e inserire quattro elementi p come sopra: Ottenere il primo paragrafo utilizzando **_document.querySelector(tagname)_** e il nome del tag
2. Ottenere ciascuno dei paragrafi utilizzando **_document.querySelector('#id')_** e il loro id.
3. Ottenere tutti i p come nodeList usando **_document.querySelectorAll(tagname)_** e in base al loro nome di tag
4. Eseguire un loop attraverso l'elenco dei nodi e ottenere il contenuto del testo di ciascun paragrafo.
5. Impostare un contenuto di testo per il quarto paragrafo,**_Quarto paragrafo_**
6. Impostare gli attributi id e class per tutti i paragrafi, utilizzando diversi metodi di impostazione degli attributi.
### EsercizioLivello 2
1. Modificare lo stile di ogni paragrafo utilizzando JavaScript (ad esempio, colore, sfondo, bordo, dimensione del carattere, tipo di carattere).
1. Selezionate tutti i paragrafi e passate in rassegna tutti gli elementi, dando al primo e al terzo paragrafo un colore verde e al secondo e al quarto un colore rosso.
1. Impostare il contenuto del testo, l'id e la classe di ogni paragrafo
### EsercizioLivello 3
#### DOM: Mini project 1
1. Sviluppare la seguente applicazione, utilizzando i seguenti elementi HTML per iniziare. Otterrete lo stesso codice nella cartella di partenza. Applicare tutti gli stili e le funzionalità utilizzando solo JavaScript.
- Il colore dell'anno cambia ogni 1 secondo
- Il colore di sfondo della data e dell'ora cambia ogni secondo.
- La sfida completata ha lo sfondo verde
- La sfida in corso ha lo sfondo giallo
- Le sfide in arrivo hanno lo sfondo rosso
```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>
```
![Project 1](../../images/projects/dom_min_project_challenge_info_day_1.1.gif)
![Project 2](../../images/projects/dom_min_project_challenge_info_day_1.1.png)
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_22.png)
- [Day 22](#day-22)
- [DOM(Document Object Model)-Day 2](#domdocument-object-model-day-2)
- [Creare un elemento](#creating-an-element)
- [Creare più elementi](#creating-elements)
- [collegare un elemento child ad un elemento parent](#appending-child-to-a-parent-element)
- [Rimuovere un elemento child da un elemento parent](#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
### Creare un elemento
Per creare un elemento HTML si usa il nome del tag. Creare un elemento HTML con JavaScript è molto semplice e immediato. Si utilizza il metodo _document.createElement()_. Il metodo prende il nome di un tag dell'elemento HTML come parametro stringa.
```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>
```
### Creare più elementi
Per creare più elementi dobbiamo usare il loop. Utilizzando il ciclo, possiamo creare tutti gli elementi HTML che vogliamo.
Dopo aver creato l'elemento, possiamo assegnare il valore alle diverse proprietà dell'oggetto HTML.
```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>
```
### collegare un elemento child ad un elemento parent
Per vedere un elemento creato nel documento HTML, dobbiamo aggiungerlo al genitore come elemento figlio. Possiamo accedere al corpo del documento HTML usando *document.body*. Il file *document.body* supporta il metodo *appendChild()*. Si veda l'esempio seguente.
```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>
```
### Rimuovere un elemento child da un elemento parent
Dopo aver creato un HTML, potremmo voler rimuovere uno o più elementi e possiamo usare il metodo *removeChild()*.
**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>
```
Come abbiamo visto nella sezione precedente, esiste un modo migliore per eliminare tutti gli elementi HTML interni o i figli di un elemento genitore, utilizzando le proprietà del metodo *innerHTML*.
```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>
```
Il frammento di codice precedente cancella tutti gli elementi figli.
---
🌕Sei così speciale, fai progressi ogni giorno. Ora sai come distruggere un elemento DOM creato quando è necessario. Hai imparato il DOM e ora hai la capacità di costruire e sviluppare applicazioni. Ti restano solo otto giorni per raggiungere la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## Esercizi
### Esercizi: Livello 1
1. Creare un div contenitore nel documento HTML e creare 100-100 numeri dinamicamente e aggiungerli al div contenitore.
- Lo sfondo dei numeri pari è verde
- Lo sfondo dei numeri dispari è giallo
- Lo sfondo dei numeri primi è rosso
![Number Generator](../../images/projects/dom_min_project_day_number_generators_2.1.png)
### Esercizi: Livello 2
1. Utilizzare l'array Paesi per visualizzare tutti i Paesi.Vedere il disegno
![World Countries List](../../images/projects/dom_min_project_countries_aray_day_2.2.png)
### Esercizi: Livello 3
Controllare i requisiti di questo progetto da entrambe le immagini (jpg e gif). Tutti i dati e i CSS sono stati implementati utilizzando solo JavaScript. I dati si trovano nella cartella starter project_3. Il pulsante a discesa è stato creato utilizzando l'elemento HTML [*details*](https://www.w3schools.com/tags/tag_details.asp).
![Challenge Information](../../images/projects/dom_mini_project_challenge_info_day_2.3.gif)
![Challenge Information](../../images/projects/dom_mini_project_challenge_info_day_2.3.png)
🎉 CONGRATULAZIONI ! 🎉
[<< Day 21](../21_Day_DOM/21_day_dom.md) | [Day 23 >>](../23_Day_Event_listeners/23_day_event_listeners.md)

@ -0,0 +1,333 @@
<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)
![Thirty Days Of JavaScript](../../images/banners/day_1_23.png)
- [Day 22](#day-22)
- [DOM(Document Object Model)-Day 3](#domdocument-object-model-day-3)
- [Event Listeners](#event-listeners)
- [Click](#click)
- [Double Click](#double-click)
- [Mouse enter](#mouse-enter)
- [Ottenere un valore da un elemento di input](#getting-value-from-an-input-element)
- [Valore di input](#input-value)
- [Valore di input ed azioni in risposta](#input-event-and-change)
- [Evento di blur](#blur-event)
- [keypress, keydow and keyup](#keypress-keydow-and-keyup)
- [Esercizi](#exercises)
- [Esercizio: Livello 1](#exercise-level-1)
# Day 22
## DOM(Document Object Model)-Day 3
### Event Listeners
Eventi HTML comuni: onclick, onchange, onmouseover, onmouseout, onkeydown, onkeyup, onload.
Possiamo aggiungere un metodo di ascolto degli eventi a qualsiasi oggetto DOM. Utilizziamo il metodo **_addEventListener()_** per ascoltare diversi tipi di eventi sugli elementi HTML. Il metodo _addEventListener()_ accetta due argomenti, un ascoltatore di eventi e una funzione di callback.
```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
Per collegare un ascoltatore di eventi a un elemento, prima si seleziona l'elemento e poi si applica il metodo addEventListener. L'ascoltatore di eventi prende come argomento il tipo di evento e le funzioni di callback.
Di seguito è riportato un esempio di evento di tipo click.
**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>
```
Un evento può anche essere allegato direttamente all'elemento HTML come script inline.
**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
Per collegare un ascoltatore di eventi a un elemento, prima si seleziona l'elemento e poi si applica il metodo addEventListener. L'ascoltatore di eventi prende come argomento il tipo di evento e le funzioni di callback.
Di seguito è riportato un esempio di evento di tipo click.
**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
Per collegare un ascoltatore di eventi a un elemento, prima si seleziona l'elemento e poi si applica il metodo addEventListener. L'ascoltatore di eventi prende come argomento il tipo di evento e le funzioni di callback.
Di seguito è riportato un esempio di evento di tipo click.
**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>
```
Ormai si conosce il metodo addEventListen e come collegare un ascoltatore di eventi. Esistono molti tipi di ascoltatori di eventi. Ma in questa sfida ci concentreremo sugli eventi più comuni e importanti.
Elenco degli eventi:
- click - quando l'elemento viene cliccato
- dblclick - quando l'elemento fa doppio clic
- mouseenter - quando il punto del mouse entra nell'elemento
- mouseleave - quando il puntatore del mouse lascia l'elemento
- mousemove - quando il puntatore del mouse si sposta sull'elemento
- mouseover - quando il puntatore del mouse si sposta sull'elemento
- mouseout - quando il puntatore del mouse esce dall'elemento
- input - quando il valore viene inserito nel campo di input
- change - quando il valore viene modificato nel campo di input
- blur - quando l'elemento non è focalizzato
- keydown - quando un tasto è abbassato
- keyup - quando un tasto viene alzato
- keypress - quando si preme un tasto qualsiasi
- onload - quando il browser ha terminato il caricamento di una pagina
Verificate i tipi di evento di cui sopra sostituendo il tipo di evento nel codice dello snippet precedente.
### Ottenere un valore da un elemento di input
Di solito compiliamo moduli e i moduli accettano dati. I campi dei moduli vengono creati utilizzando l'elemento HTML input. Costruiamo una piccola applicazione che ci consenta di calcolare l'indice di massa corporea di una persona utilizzando due campi di input, un pulsante e un tag p.
### Valore di input
```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>
```
#### Valore di input ed azioni in risposta
Nell'esempio precedente, siamo riusciti a ottenere il valore di input da due campi di input facendo clic sul pulsante. E se volessimo ottenere il valore senza fare clic sul pulsante? Possiamo usare il tipo di evento _change_ o _input_ per ottenere subito i dati dal campo di input quando il campo è a fuoco. Vediamo come gestirlo.
```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>
```
#### Evento di blur
A differenza di _input_ o _change_, l'evento _blur_ si verifica quando il campo di input non è a fuoco.
```js
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<h1>Giving feedback using Evento di blur</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
Possiamo accedere a tutti i numeri dei tasti della tastiera utilizzando diversi tipi di ascoltatori di eventi. Utilizziamo keypress e otteniamo il keyCode di ogni tasto della tastiera.
```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>
```
---
🌕 Sei così speciale, progredisci ogni giorno. Ora, sai come gestire qualsiasi tipo di evento DOM. . Ti restano solo sette giorni per raggiungere la grandezza. Ora fai qualche esercizio per il cervello e per i muscoli.
## Esercizi
### Exercise: Livello 1
1. Generazione di numeri e marcatura di pari, dispari e numeri primi con tre colori diversi. Vedere l'immagine qui sotto.
![Number Generator](../../images/projects/dom_min_project_number_generator_day_3.1.gif)
1. Generazione del codice della tastiera utilizzando l'ascoltatore Even. L'immagine seguente.
![Keyboard key](../../images/projects/dom_min_project_keycode_day_3.2.gif)
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_24.png)
- [Day 24](#day-24)
- [Esercizi](#exercises)
- [Esercizio: Livello 1](#exercise-level-1)
# Day 24
## Esercizi
### Exercise: Livello 1
1. Sviluppare una piccola applicazione che calcoli il peso di un oggetto in un determinato pianeta. L'immagine gif non è completa, controllate il video nel file di partenza.
![Solar System](../../images/projects/dom_min_project_solar_system_day_4.1.gif)
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_25.png)
- [Day 25](#day-25)
- [Esercizi](#exercises)
- [Esercizio: Livello 1](#exercise-level-1)
# Day 25
## Esercizi
### Exercise: Livello 1
1. Visualizzare i dieci Paesi più popolati e le dieci lingue più parlate al mondo utilizzando DOM (HTML, CSS, JS).
![Bar Graph](../../images/projects/dom_min_project_bar_graph_day_5.1.gif)
![Bar Graph](../../images/projects/dom_min_project_bar_graph_day_5.1.png)
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_26.png)
- [Day 26](#day-26)
- [Esercizi](#exercises)
- [Esercizio: Livello 1](#exercise-level-1)
# Day 26
## Esercizi
### Exercise: Livello 1
1. Visualizzare l'array dei Paesi come segue
![Motivation](../../images/projects/dom_mini_project_countries_day_6.1.gif)
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_27.png)
- [Day 27](#day-27)
- [Esercizi](#exercises)
- [Esercizio: Livello 1](#exercise-level-1)
# Day 27
## Esercizi
### Exercise: Livello 1
1. Creare quanto segue utilizzando HTML, CSS e JavaScript
![Slider](../../images/projects/dom_mini_project_slider_day_7.1.gif)
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_28.png)
- [Day 28](#day-28)
- [Esercizi](#exercises)
- [Esercizio: Livello 1](#exercise-level-1)
# Day 28
## Esercizi
### Exercise: Livello 1
1. Creare quanto segue utilizzando HTML, CSS e JavaScript
![Slider](../../images/projects/dom_mini_project_leaderboard_day_8.1.gif)
🎉 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_29.png)
- [Day 29](#day-29)
- [Esercizi](#exercises)
- [Esercizio: Livello 1](#exercise-level-1)
- [Esercizio: Livello 2](#exercise-level-2)
- [Esercizio: Livello 3](#exercise-level-3)
# Day 29
## Esercizi
### Exercise: Livello 1
1. Creare la seguente animazione utilizzando (HTML, CSS, JS)
![Slider](../../images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif)
### 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)
![Thirty Days Of JavaScript](../../images/banners/day_1_30.png)
- [Day 30](#day-30)
- [Esercizi](#exercises)
- [Esercizio: Livello 1](#exercise-level-1)
- [Esercizio: Livello 2](#exercise-level-2)
- [Esercizio: Livello 3](#exercise-level-3)
- [Testimony](#testimony)
- [Support](#support)
# Day 30
## Esercizi
### Exercise: Livello 1
1. Creare la seguente animazione utilizzando (HTML, CSS, JS)
![Countries data](../../images/projects/dom_mini_project_countries_object_day_10.1.gif)
2. Convalidare il seguente modulo utilizzando una regex.
![form validation](../../images/projects/dom_mini_project_form_validation_day_10.2.1.png)
![form validation](../../images/projects/dom_mini_project_form_validation_day_10.2.png)
### Exercise: Livello 2
### Exercise: Livello 3
🌕Il tuo viaggio verso la grandezza si è concluso con successo. Hai raggiunto un alto livello di grandezza. Ora sei molto più grande di prima. Sapevo cosa ci voleva per raggiungere questo Livello e tu sei arrivato a questo punto. Sei un vero eroe. Ora è il momento di festeggiare il tuo successo con un amico o con la tua famiglia. Non vedo l'ora di vederti in un'altra sfida.
## Testimony
Ora è il momento di sostenere l'autore e di esprimere il tuo pensiero sull'autore e su 30DaysOfJavaScript. Potete lasciare la vostra testimonianza su questo [link](https://testimonify.herokuapp.com/)
## Support
Potete sostenere l'autore nella produzione di ulteriori materiali didattici.
[![paypal](../../images/paypal_lg.png)](https://www.paypal.me/asabeneh)
![Congratulations](../../images/projects/congratulations.gif)
[<< Day 29](../29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md)

@ -0,0 +1,813 @@
# 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)
![Thirty Days Of JavaScript](../images/day_1_1.png)
- [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/).
![Node download](../images/download_node.png)
Dopo aver scaricato il file aprilo ed installa node
![Installazione node](../images/install_node.png)
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.
![Google Chrome](../images/google_chrome.png)
#### 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.
![Opening chrome](../images/opening_developer_tool.png)
Per aprire la console di Chrome utilizzando una scorciatoia da tastiera
```sh
Mac
Command+Option+J
Windows/Linux:
Ctl+Shift+J
```
![Opening console](../images/opening_chrome_console_shortcut.png)
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:
![write code on console](../images/js_code_on_chrome_console.png)
#### 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)`**
![console log multiple arguments](../images/console_log_multipl_arguments.png)
```js
console.log('Hello', 'World', '!')
console.log('HAPPY', 'NEW', 'YEAR', 2020)
console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript')
```
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.
![Error](../images/raising_syntax_error.png)
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.
![Arithmetic](../images/arithmetic.png)
```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.
![Vscode](../images/vscode.png)
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.
![Vscode ui](../images/vscode_ui.png)
![Vscode add project](../images/adding_project_to_vscode.png)
![Vscode open project](../images/opening_project_on_vscode.png)
![script file](../images/scripts_on_vscode.png)
![Installazione Live Server](../images/vsc_live_server.png)
![running script](../images/running_script.png)
![coding running](../images/launched_on_new_tab.png)
## 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()`.
![js code from vscode](../images/js_code_vscode.png)
### 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.
![Multiple Script](../images/multiple_script.png)
## 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:
![Giorno one](../images/day_1.png)
🌕 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)

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 338 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 509 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 234 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save