Merge branch 'Asabeneh:master' into master

pull/511/head
Bread 3 years ago committed by GitHub
commit 84d74d7acc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -82,9 +82,7 @@ ReferenceError: fistName is not defined
at <anonymous>:4:20 at <anonymous>:4:20
In any case it will be executed In any case it will be executed
``` ```
The catch block take a parameter. It is common to pass e, err or error as a parameter to the catch block. This parameter is an object and it has name and message keys. Lets use the name and message. The catch block take a parameter. It is common to pass e, err or error as a parameter to the catch block. This parameter is an object and it has name and message keys. Lets use the name and message.
```js ```js
try { try {
let lastName = 'Yetayeh' let lastName = 'Yetayeh'
@ -96,22 +94,18 @@ try {
console.log('In any case I will be executed') console.log('In any case I will be executed')
} }
``` ```
```sh ```sh
Name of the error ReferenceError Name of the error ReferenceError
Error message fistName is not defined Error message fistName is not defined
In any case I will be executed In any case I will be executed
``` ```
throw: the throw statement allows us to create a custom error. We can through a string, number, boolean or an object. Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception: throw: the throw statement allows us to create a custom error. We can through a string, number, boolean or an object. Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:
```js ```js
throw 'Error2' // generates an exception with a string value throw 'Error2' // generates an exception with a string value
throw 42 // generates an exception with the value 42 throw 42 // generates an exception with the value 42
throw true // generates an exception with the value true throw true // generates an exception with the value true
throw new Error('Required') // generates an error object with the message of Required throw new Error('Required') // generates an error object with the message of Required
``` ```
```js ```js
const throwErrorExampleFun = () => { const throwErrorExampleFun = () => {
let message let message
@ -128,66 +122,43 @@ const throwErrorExampleFun = () => {
} }
throwErrorExampleFun() throwErrorExampleFun()
``` ```
### Error Types ### Error Types
- ReferenceError: An illegal reference has occurred. A ReferenceError is thrown if we use a variable that has not been declared. - ReferenceError: An illegal reference has occurred. A ReferenceError is thrown if we use a variable that has not been declared.
```js ```js
let firstName = 'Asabeneh' let firstName = 'Asabeneh'
let fullName = firstName + ' ' + lastName let fullName = firstName + ' ' + lastName
console.log(fullName) console.log(fullName)
``` ```
```sh ```sh
Uncaught ReferenceError: lastName is not defined Uncaught ReferenceError: lastName is not defined
at <anonymous>:2:35 at <anonymous>:2:35
``` ```
- SyntaxError: A syntax error has occurred - SyntaxError: A syntax error has occurred
```js ```js
let square = 2 x 2 let square = 2 x 2
console.log(square) console.log(square)
console.log('Hello, world") console.log('Hello, world")
``` ```
```sh ```sh
Uncaught SyntaxError: Unexpected identifier Uncaught SyntaxError: Unexpected identifier
``` ```
- TypeError: A type error has occurred - TypeError: A type error has occurred
```js ```js
let num = 10 let num = 10
console.log(num.toLowerCase()) console.log(num.toLowerCase())
``` ```
```sh ```sh
Uncaught TypeError: num.toLowerCase is not a function Uncaught TypeError: num.toLowerCase is not a function
at <anonymous>:2:17 at <anonymous>:2:17
``` ```
These are some of the common error you may face when you write a code. Understanding errors can help you to know what mistakes you made and it will help you to debug your code fast. These are some of the common error you may face when you write a code. Understanding errors can help you to know what mistakes you made and it will help you to debug your code fast.
🌕 You are flawless. Now, you knew how to handle errors and you can write robust application which handle unexpected user inputs. You have just completed day 14 challenges and you are 14 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. 🌕 You are flawless. Now, you knew how to handle errors and you can write robust application which handle unexpected user inputs. You have just completed day 14 challenges and you are 14 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle.
## Exercises ## Exercises
### Exercises:Level 1 ### Exercises:Level 1
Practice Practice
### Exercises: Level 2 ### Exercises: Level 2
Practice Practice
### Exercises:Level ### Exercises:Level
Practice Practice
🎉 CONGRATULATIONS ! 🎉 🎉 CONGRATULATIONS ! 🎉
[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md)
[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md)

@ -14,7 +14,7 @@
</div> </div>
[<< Day 2](../dia_02_tipos_de_datos.md) | [Day 4 >>](../dia_04_Condicionales/dia_04_Condicionales.md) [<< Día 2](../dia_02_tipos_de_datos.md) | [Día 4 >>](../dia_04_Condicionales/dia_04_Condicionales.md)
![Thirty Days Of JavaScript](../images/banners/day_1_3.png) ![Thirty Days Of JavaScript](../images/banners/day_1_3.png)
@ -126,7 +126,7 @@ Los operadores aritméticos son operadores matemáticos.
- Suma(+): a + b - Suma(+): a + b
- Resta(-): a - b - Resta(-): a - b
- Multiplicación(_): a _ b - Multiplicación(\*): a \* b
- División(/): a / b - División(/): a / b
- Módulo(%): a % b - Módulo(%): a % b
- Exponencial(**): a ** b - Exponencial(**): a ** b
@ -629,4 +629,4 @@ console.log(`${date}/${month}/${year} ${hours}:${minutes}`); // 4/1/2020 0:56
1. Cree un formato de hora legible por humanos usando el objeto Date. La hora y el minuto deben ser siempre dos dígitos (7 horas deben ser 07 y 5 minutos deben ser 05) 1. Cree un formato de hora legible por humanos usando el objeto Date. La hora y el minuto deben ser siempre dos dígitos (7 horas deben ser 07 y 5 minutos deben ser 05)
1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05 1. YYY-MM-DD HH:mm eg. 20120-01-02 07:05
[<< Day 2](../dia_02_tipos_de_datos.md) | [Day 4 >>](../dia_04_Condicionales/dia_04_Condicionales.md) [<< Día 2](../dia_02_tipos_de_datos.md) | [Día 4 >>](../dia_04_Condicionales/dia_04_Condicionales.md)

@ -778,4 +778,4 @@ const webTechs = [
🎉 ¡Felicitaciones! 🎉 🎉 ¡Felicitaciones! 🎉
[<< Day 4](../dia_04_Condicionales/dia_04_Condicionales.md) | [Day 6 >>](../dia_06_Bucles/dia_06_bucles.md) [<< Día 4](../dia_04_Condicionales/dia_04_Condicionales.md) | [Día 6 >>](../dia_06_Bucles/dia_06_bucles.md)

@ -14,7 +14,7 @@
</div> </div>
[<< Day 6](../dia_06_Bucles/dia_06_bucles.md) | [Día 8 >>](../dia_08_Objetos/dia_08_objetos.md) [<< Día 6](../dia_06_Bucles/dia_06_bucles.md) | [Día 8 >>](../dia_08_Objetos/dia_08_objetos.md)
![Thirty Days Of JavaScript](../images/banners/day_1_7.png) ![Thirty Days Of JavaScript](../images/banners/day_1_7.png)
@ -699,4 +699,4 @@ Será cubierto en otra sección.
1. Escriba una función llamada reverseCountries, toma el array de países y primero copia el array y retorna el array original invertido 1. Escriba una función llamada reverseCountries, toma el array de países y primero copia el array y retorna el array original invertido
🎉 ¡FELICITACIONES! 🎉 🎉 ¡FELICITACIONES! 🎉
[<< Day 6](../dia_06_Bucles/dia_06_bucles.md) | [Day 8 >>](../dia_08_Objetos/dia_08_objetos.md) [<< Día 6](../dia_06_Bucles/dia_06_bucles.md) | [Día 8 >>](../dia_08_Objetos/dia_08_objetos.md)

@ -704,4 +704,4 @@ const products = [
🎉 ¡FELICITACIONES! 🎉 🎉 ¡FELICITACIONES! 🎉
[<< Día 8](../dia_08_Objetos/dia_08_objetos.md) | [Day 10 >>](../dia_10_Sets_y_Maps/dia_10_sets_y_maps.md) [<< Día 8](../dia_08_Objetos/dia_08_objetos.md) | [Día 10 >>](../dia_10_Sets_y_Maps/dia_10_sets_y_maps.md)

@ -14,7 +14,7 @@
</div> </div>
[<< Día 16](../dia_16_JSON/dia_16_json.md) | [Día 18 >>](..) [<< Día 16](../dia_16_JSON/dia_16_json.md) | [Día 18 >>](../dia_18_Promesas/dia_18_Promesas.md)
![Thirty Days Of JavaScript](../images/banners/day_1_17.png) ![Thirty Days Of JavaScript](../images/banners/day_1_17.png)
@ -230,4 +230,4 @@ localStorage.clear();
🎉 ¡FELICITACIONES! 🎉 🎉 ¡FELICITACIONES! 🎉
[<< Día 16](../dia_16_JSON/dia_16_json.md) | [Día 18 >>](..) [<< Día 16](../dia_16_JSON/dia_16_json.md) | [Día 18 >>](../dia_18_Promesas/dia_18_Promesas.md)

@ -0,0 +1,273 @@
<div align="center">
<h1> 30 Días de JavaScript: Promesas</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 17](../dia_17_Web_storages/dia_17_web_storages.md) | [Día 19>>](../dia_19_Closures/dia_19_closures.md)
![Thirty Days Of JavaScript](../images/banners/day_1_18.png)
- [Día 18](#día-18)
- [Promesas](#promesas)
- [Callbacks](#callbacks)
- [Constructor de promesas](#constructor-de-promesas)
- [Fetch API](#fetch-api)
- [Async y Await](#async-y-await)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
- [Ejercicios: Nivel 2](#ejercicios-nivel-2)
- [Ejercicios: Nivel 3](#ejercicios-nivel-3)
# Día 18
## Promesas
Los seres humanos damos o recibimos una promesa para realizar alguna actividad en algún momento. Si cumplimos la promesa, hacemos felices a los demás, pero si no la cumplimos, puede provocar descontento. La promesa en JavaScript tiene algo en común con los ejemplos anteriores.
Una promesa es una forma de manejar operaciones asíncronas en JavaScript. Permite a los manejadores con un valor eventual de éxito o razón de fracaso de una acción asíncrona. Esto permite que los métodos asíncronos devuelvan valores como los métodos síncronos: en lugar de devolver inmediatamente el valor final, el método asíncrono devuelve una promesa de proporcionar el valor en algún momento en el futuro.
Una promesa está en uno de estos estados:
- pendiente: estado inicial, ni cumplido ni rechazado.
- cumplido: significa que la operación se ha completado con éxito.
- rechazado: significa que la operación ha fallado.
Una promesa pendiente puede ser cumplida con un valor, o rechazada con una razón (error). Cuando ocurre cualquiera de estas opciones, se llaman los manejadores asociados puestos en cola por el método _then_ de una promesa. (Si la promesa ya se ha cumplido o ha sido rechazada cuando se adjunta un manejador correspondiente, se llamará al manejador, por lo que no hay una condición de competencia entre una operación asíncrona que se completa y sus manejadores que se adjuntan).
Como los métodos _Promise.prototype.then()_ y _Promise.prototype.catch()_ devuelven promesas, pueden encadenarse.
## Callbacks
Para entender muy bien la promesa, entendamos primero la devolución de llamada. Veamos los siguientes callbacks. A partir de los siguientes bloques de código se notará, la diferencia entre callback y promesas.
- call back
Veamos una función callback que puede tomar dos parámetros. El primer parámetro es err y el segundo es result. Si el parámetro err es falso, no habrá error, de lo contrario retornará un error.
En este caso el err tiene un valor y devolverá el bloque 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
// después de 2 segundos se imprimirá
It did not go well
```
En este caso el err es falso y devolverá el bloque else que es el resultado.
```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
// después de 2 segundos imprimirá las habilidades
["HTML", "CSS", "JS"]
```
### Constructor de promesas
Podemos crear una promesa utilizando el constructor Promise. Podemos crear una nueva promesa utilizando la palabra clave `new` seguida de la palabra `Promise` y seguida de un paréntesis. Dentro del paréntesis, toma una función `callback`. La función de callback de la promesa tiene dos parámetros que son las funciones _`resolve`_ y _`reject`_.
```js
// sintaxis
const promise = new Promise((resolve, reject) => {
resolve("success");
reject("failure");
});
```
```js
// Promesas
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 promesa anterior se ha resuelto con resolución.
Veamos otro ejemplo cuando la promesa se resuelve con el rechazo (reject).
```js
// Promesa
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
La API Fetch proporciona una interfaz para obtener recursos (incluso a través de la red). A cualquiera que haya utilizado XMLHttpRequest le resultará familiar, pero la nueva API ofrece un conjunto de funciones más potente y flexible. En este reto utilizaremos fetch para solicitar url y APIS. Además de esto, veamos una demostración del caso de uso de las promesas en el acceso a los recursos de la red utilizando la API fetch.
```js
const url = "https://restcountries.com/v2/all"; // api de países
fetch(url)
.then((response) => response.json()) // acceder a los datos de la API como JSON
.then((data) => {
// obtener los datos
console.log(data);
})
.catch((error) => console.error(error)); // manejo de errores si ocurre algo incorrecto
```
## Async y Await
Async y await es una forma elegante de manejar las promesas. Es fácil de entender y limpio de escribir.
```js
const square = async function (n) {
return n * n;
};
square(2);
```
```sh
Promesa {<resolved>: 4}
```
La palabra _async_ delante de una función significa que esa función devolverá una promesa. La función cuadrada anterior en lugar de un valor devuelve una promesa.
¿Cómo accedemos al valor de la promesa? Para acceder al valor de la promesa, utilizaremos la palabra clave _await_.
```js
const square = async function (n) {
return n * n;
};
const value = await square(2);
console.log(value);
```
```sh
4
```
Ahora, como puedes ver en el ejemplo anterior escribiendo async delante de una función creamos una promesa y para obtener el valor de una promesa utilizamos await. Async y await van juntos, uno no puede existir sin el otro.
Vamos a obtener los datos de la API utilizando tanto el método promise como el método async y await.
- promesa
```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 y 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();
```
🌕 Eres consistente y has cumplido tu promesa, has llegado al día 18. Mantén tu promesa y resuelve el desafío con determinación. Has dado 18 pasos adelante en tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y tus músculos.
## Ejercicios
```js
const countriesAPI = "https://restcountries.com/v2/all";
const catsAPI = "https://api.thecatapi.com/v1/breeds";
```
### Ejercicios: Nivel 1
1. Lee la API de los países utilizando fetch e imprime el nombre del país, la capital, los idiomas, la población y la superficie.
### Ejercicios: Nivel 2
1. Imprime todos los nombres de los gatos en la variable catNames.
### Ejercicios: Nivel 3
1. Lee el api de los gatos y encuentra el peso medio del gato en unidad métrica.
2. Lee la api de países y descubre los 10 países más grandes
3. Lea la api de los países y cuente el número total de lenguas del mundo utilizadas como oficiales.
🎉 ¡FELICITACIONES! 🎉
[<< Día 17](../dia_17_Web_storages/dia_17_web_storages.md) | [Día 19>>](../dia_19_Closures/dia_19_closures.md)

@ -0,0 +1,105 @@
<div align="center">
<h1> 30 Días de 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>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 18](../dia_18_Promesas/dia_18_Promesas.md) | [Día 20 >>](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md)
![Thirty Days Of JavaScript](../images/banners/day_1_19.png)
- [Día 19](#día-19)
- [Closure](#closure)
- [Ejercicios](#exercises)
- [Ejercicios: Nivel 1](#exercises-level-1)
- [Ejercicios: Nivel 2](#exercises-level-2)
- [Ejercicios: Nivel 3](#exercises-level-3)
# Día 19
## Closure
JavaScript permite escribir una función dentro de una función externa. Podemos escribir tantas funciones internas como queramos. Si la función interna accede a las variables de la función externa entonces se llama closure (clausura).
```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
```
Veamos más ejemplos de funciones internas
```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
```
🌕 Estás haciendo progresos. Mantén tu ritmo, sigue con el buen trabajo. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
## Ejercicios
### Ejercicios: Nivel 1
1. Crear una closure que tenga una función interna
### Ejercicios: Nivel 2
1. Crear una closure que tenga tres funciones internas
### Ejercicios: Nivel 3
1. Crear una función de salida de personAccount. Tiene variables internas de nombre, apellido, ingresos y gastos. Tiene las funciones internas totalIncome, totalExpense, accountInfo,addIncome, addExpense y accountBalance. Los ingresos son un conjunto de ingresos y su descripción y los gastos son también un conjunto de gastos con su descripción.
🎉 ¡FELICITACIONES! 🎉
[<< Día 18](../dia_18_Promesas/dia_18_Promesas.md) | [Día 20 >>](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md)

@ -0,0 +1,376 @@
<div align="center">
<h1> 30 Días de JavaScript: Escribiendo Códigos Limpios</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 19](../dia_19_Closures/dia_19_closures.md) | [Día 21 >>](../dia_21_DOM/dia_21_dom.md)
![Thirty Days Of JavaScript](../images/banners/day_1_20.png)
- [Día 20](#día-20)
- [Escribiendo código limpio](#escribiendo-código-limpio)
- [Guía de estilo JavaScript](#guía-de-estilo-javascript)
- [¿Por qué necesitamos una guía de estilo?](#¿por-qué-necesitamos-una-guía-de-estilo)
- [Guía de estilo JavaScript de Airbnb](#guía-de-estilo-javascript-de-airbnb)
- [Guía de estilo estándar de JavaScript](#guía-de-estilo-estándar-de-javascript)
- [Guía de estilo JavaScript de Google](#guía-de-estilo-javascript-de-google)
- [Convenciones de codificación en JavaScript](#convenciones-de-codificación-en-javascript)
- [Convenciones usadas en 30DíasDeJavaScript](#convenciones-usadas-en-30díasdejavascript)
- [Variables](#variables)
- [Arrays](#arrays)
- [Funciones](#funciones)
- [Bucles](#bucles)
- [Objetos](#objetos)
- [Condicional](#condicional)
- [Clases](#clases)
# Día 20
## Escribiendo código limpio
### Guía de estilo JavaScript
Una guía de estilo de JavaScript es un conjunto de normas que indica cómo debe escribirse y organizarse el código de JavaScript. En esta sección, hablaremos de las guías de JavaScript y de cómo escribir un código limpio.
JavaScript es un lenguaje de programación, como el lenguaje humano, tiene una sintaxis. La sintaxis de JavaScript debe escribirse siguiendo una determinada pauta de estilo para convencer y simplificar.
### ¿Por qué necesitamos una guía de estilo?
Has estado codificando solo durante mucho tiempo, pero ahora parece que trabajas en equipo. No importa de qué manera escribas tu código, siempre y cuando funcione, sin embargo, cuando trabajas en un equipo de 10, 20 o más desarrolladores en un proyecto y en la misma base de código, el código será desordenado y difícil de manejar si no hay ninguna guía a seguir.
Puede desarrollar sus propias directrices y convenciones o también puede adaptar directrices bien desarrolladas. Conozcamos las guías más comunes.
Guías de estilo de JavaScript más comunes
- Guía de estilo JavaScript de Airbnb
- Guía de estilo estándar de JavaScript
- Guía de estilo JavaScript de Google
#### Guía de estilo JavaScript de Airbnb
Airbnb tiene una de las guías de estilo JavaScript más populares de Internet. También cubre casi todos los aspectos de JavaScript y es adoptado por muchos desarrolladores y empresas. Puede consultar la [Guía de estilo de Airbnb](https://github.com/airbnb/javascript). Yo también recomendaría probarlo. Su estilo es muy fácil de usar y sencillo de entender.
#### Guía de estilo estándar de JavaScript
Esta guía no es tan popular como la de Airbnb, pero merece la pena echarle un vistazo. Han eliminado el punto y coma en su [guía de estilo](https://standardjs.com/).
#### Guía de estilo JavaScript de Google
No diré mucho sobre la guía de Google. No las he usado, más bien te sugiero que eches un vistazo desde este [link](https://google.github.io/styleguide/jsguide.html).
### Convenciones de codificación en JavaScript
En este desafío también utilizamos las convenciones y guías generales de codificación de JavaScript. Las convenciones de codificación son pautas de estilo de programación desarrolladas por un individuo, un equipo o una empresa.
Las convenciones de codificación ayudan:
- para escribir un código limpio
- para mejorar la legibilidad del código
- para mejorar la reutilización y el mantenimiento del código
Las convenciones de codificación incluyen
- Reglas de declaración y denominación de las variables
- Reglas de declaración y denominación de las funciones
- Reglas para el uso de espacios en blanco, sangría y comentarios
- Prácticas y principios de programación
#### Convenciones usadas en 30DíasDeJavaScript
En este reto seguimos la convención habitual de JavaScript pero he añadido también mi preferencia de escritura.
- Utilizamos camelCase para las variables y las funciones.
- Todos los nombres de las variables comienzan con una letra.
- Hemos optado por utilizar _const_ para las constantes, los arrays, los objetos y las funciones. En lugar de las comillas dobles, hemos optado por utilizar las comillas simples o backtick. Las comillas simples se están poniendo de moda.
- También hemos eliminado el punto y coma de nuestro código, pero es una cuestión de preferencia personal.
- Espacio alrededor de los operadores aritméticos, operadores de asignación y después de la coma
- Función de flecha en lugar de declaración de función
- Retorno explícito en lugar de implícito si la función es de una línea
- No hay coma final en el último valor de un objeto
- Preferimos este +=, -=, \*= /=, \*\*= en lugar de la versión más larga
- Cuando usamos console.log() es bueno imprimir con una cadena de etiquetas para identificar de dónde viene la consola
#### Variables
```js
let firstName = "Asabeneh";
let lastName = "Yetayeh";
let country = "Finland";
let city = "Helsinki";
const PI = Math.PI;
const gravity = 9.81;
```
#### Arrays
Hemos optado por hacer que los nombres de los arrays sean plurales
- 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"];
```
#### Funciones
A estas alturas ya estás muy familiarizado con la declaración de funciones, la función de expresión, la función de flecha y la función anónima. En este reto tendemos a utilizar la función de flecha en lugar de otras funciones. La función flecha no sustituye a otras funciones. Además, las funciones de flecha y las declaraciones de función no son exactamente iguales. Por lo tanto, debes saber cuándo usarla y cuándo no. En otras secciones trataré la diferencia en detalle. Utilizaremos el retorno explícito en lugar del implícito si la función es de una sola línea.
```js
// función que devuelve el nombre completo de una persona
const printFullName = (firstName, lastName) => firstName + " " + lastName;
// función que calcula el cuadrado de un número
const square = (n) => n * n;
// una función que genera colores hexa al azar
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;
};
// una función que muestra la fecha y la hora
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;
};
```
La función `new Dat().toLocaleString()` también puede utilizarse para mostrar la fecha y hora actuales. Los métodos `toLocaleString()` toman diferentes argumentos. Puede aprender más sobre la fecha y la hora en este [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString).
#### Bucles
En estos retos cubrimos muchos tipos de bucles. El bucle regular for, el bucle while, el bucle do while, el bucle for of, el bucle forEach y el bucle for in.
Veamos cómo los utilizamos:
```js
for (let i = 0; i < n; i++) {
console.log();
}
// declaración de una variable array
const names = ["Asabeneh", "Mathias", "Elias", "Brook"];
// iteración de un array mediante un bucle for regular
let len = names.length;
for (let i = 0; i < len; i++) {
console.log(names[i].toUpperCase());
}
// iteración de un array mediante for of
for (const name of names) {
console.log(name.toUpperCase());
}
// iteración de un array mediante 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);
}
```
#### Objetos
Declaramos el objeto literal con _const_.
```js
// declarando el objeto 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,
};
// iterar a través de las claves del objeto
for (const key in person) {
console.log(key, person[key]);
}
```
#### Condicional
Hemos dicho if, if else, else, switch y operadores ternarios en los retos anteriores.
```js
// sintaxis
if (condition) {
// esta parte del código se ejecuta para la condición de verdad
} else {
// esta parte del código se ejecuta para una condición falsa
}
```
```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 Más Ejemplos
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
// ternario
let isRaining = true;
isRaining
? console.log("You need a rain coat.")
: console.log("No need for a rain coat.");
```
#### Clases
Declaramos la clase con CamelCase que empieza con mayúscula.
```js
// sintaxis
class ClassName {
// el código va aquí
}
```
```js
// definir la clase
class Person {
constructor(firstName, lastName) {
console.log(this); // Compruebe el resultado desde aquí
this.firstName = firstName;
this.lastName = lastName;
}
}
```
Sea cual sea la guía de estilo que sigas, sé coherente. Sigue algunos paradigmas de programación y patrones de diseño. Recuerda que si no escribes tu código en cierto orden o forma, será difícil leerlo. Así que hazte un favor a ti mismo o a alguien que vaya a leer tu código escribiendo código legible.
🌕 Eres ordenado. Ahora, has aprendido a escribir un código limpio, para que cualquiera que conozca el idioma inglés pueda entender tu código.Siempre estás progresando y llevas 20 pasos en tu camino hacia la grandeza.
🎉 ¡FELICITACIONES! 🎉
[<< Día 19](../dia_19_Closures/dia_19_closures.md) | [Día 21 >>](../dia_21_DOM/dia_21_dom.md)

@ -0,0 +1,407 @@
<div align="center">
<h1> 30 Días de 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>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 20](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md) | [Día 22 >>](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md)
![Thirty Days Of JavaScript](../images/banners/day_1_21.png)
- [Día 21](#día-21)
- [Document Object Model (DOM) - Día 1](#document-object-model-dom---día-1)
- [Obtención del elemento](#obtención-del-elemento)
- [Obtener elementos por nombre de etiqueta](#obtener-elementos-por-nombre-de-etiqueta)
- [Obtener elementos por el nombre de la clase](#obtener-elementos-por-el-nombre-de-la-clase)
- [Obtener un elemento por id](#obtener-un-elemento-por-id)
- [Obtener elementos mediante métodos querySelector](#obtener-elementos-mediante-métodos-queryselector)
- [Añadir atributo](#añadir-atributo)
- [Añadir un atributo con setAttribute](#añadir-un-atributo-con-setattribute)
- [Añadir atributo sin setAttribute](#añadir-atributo-sin-setattribute)
- [Añadir una clase mediante classList](#añadir-una-clase-mediante-classlist)
- [Eliminación de la clase mediante remove](#eliminación-de-la-clase-mediante-remove)
- [Añadir texto a un elemento HTML](#añadir-texto-a-un-elemento-html)
- [Añadir contenido de texto usando textContent](#añadir-contenido-de-texto-usando-textcontent)
- [Añadir contenido de texto usando innerHTML](#añadir-contenido-de-texto-usando-innerhtml)
- [textContent](#textcontent)
- [innerHTML](#innerhtml)
- [Añadir estilo](#añadir-estilo)
- [Añadir estilo color](#añadir-estilo-color)
- [Añadir estilo Background Color](#añadir-estilo-background-color)
- [Añadir estilo Font Size](#añadir-estilo-font-size)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
- [Ejercicios: Nivel 2](#ejercicios-nivel-2)
- [Ejercicios: Nivel 3](#ejercicios-nivel-3)
- [DOM: Mini proyecto 1](#dom-mini-proyecto-1)
# Día 21
## Document Object Model (DOM) - Día 1
El documento HTML está estructurado como un objeto JavaScript. Cada elemento HTML tiene diferentes propiedades que pueden ayudar a manipularlo. Es posible obtener, crear, añadir o eliminar elementos HTML mediante JavaScript. Compruebe los ejemplos siguientes. La selección de elementos HTML mediante JavaScript es similar a la selección mediante CSS. Para seleccionar un elemento HTML, utilizamos el nombre de la etiqueta, el id, el nombre de la clase u otros atributos.
### Obtención del elemento
Podemos acceder al elemento o elementos ya creados mediante JavaScript. Para acceder u obtener elementos utilizamos diferentes métodos. El código siguiente tiene cuatro elementos _h1_. Veamos los diferentes métodos para acceder a los elementos _h1_.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document Object Model - (Modelo de objeto de documento)</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>
```
#### Obtener elementos por nombre de etiqueta
**_getElementsByTagName()_**:toma un nombre de etiqueta como parámetro de cadena y este método devuelve un objeto HTMLCollection. Una HTMLCollection es un objeto tipo array de elementos HTML. La propiedad length proporciona el tamaño de la colección. Siempre que usamos este método accedemos a los elementos individuales usando el índice o después de hacer un bucle a través de cada elemento individual. Un HTMLCollection no soporta todos los métodos de los arrays, por lo que deberíamos utilizar un bucle for normal en lugar de forEach.
```js
// sintaxis
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]); // imprime cada uno de los elementos de la HTMLCollection
}
```
#### Obtener elementos por el nombre de la clase
El método **_getElementsByClassName()_** devuelve un objeto HTMLCollection. Una HTMLCollection es una lista tipo array de elementos HTML. La propiedad length proporciona el tamaño de la colección. Es posible realizar un bucle a través de todos los elementos de HTMLCollection. Vea el siguiente ejemplo
```js
//sintaxis
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]); // imprime cada uno de los elementos de la HTMLCollection
}
```
#### Obtener un elemento por id
**_getElementsById()_** tiene como objetivo un único elemento HTML. Pasamos el id sin # como argumento.
```js
//sintaxis
document.getElementById("id");
```
```js
let firstTitle = document.getElementById("first-title");
console.log(firstTitle); // <h1>First Title</h1>
```
#### Obtener elementos mediante métodos querySelector
El método _document.querySelector_ puede seleccionar un HTML o elementos HTML por nombre de etiqueta, por id o por nombre de clase.
**_querySelector_**: se puede utilizar para seleccionar elementos HTML por su nombre de etiqueta, id o clase. Si se utiliza el nombre de la etiqueta, sólo se selecciona el primer elemento.
```js
let firstTitle = document.querySelector("h1"); // seleccionar el primer elemento h1 disponible
let firstTitle = document.querySelector("#first-title"); // selecciona el id con first-title
let firstTitle = document.querySelector(".title"); // seleccionar el primer elemento disponible con clase title
```
**_querySelectorAll_**: se puede utilizar para seleccionar elementos html por su nombre de etiqueta o clase. Devuelve un nodeList que es un objeto tipo array que soporta métodos de array. Podemos utilizar **_bucle for_** o **_forEach_** para recorrer cada elemento de nodeList.
```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') // lo mismo ocurre con la selección mediante la clase
```
### Añadir atributo
En la etiqueta de apertura de HTML se añade un atributo que proporciona información adicional sobre el elemento. Atributos HTML comunes: id, class, src, style, href, disabled, title, alt. Añadamos id y class para el cuarto título.
```js
const titles = document.querySelectorAll("h1");
titles[3].className = "title";
titles[3].id = "fourth-title";
```
#### Añadir un atributo con setAttribute
El método **_setAttribute()_** establece cualquier atributo html. Toma dos parámetros: el tipo de atributo y el nombre del atributo.
Agreguemos la clase y el atributo id para el cuarto título.
```js
const titles = document.querySelectorAll("h1");
titles[3].setAttribute("class", "title");
titles[3].setAttribute("id", "fourth-title");
```
#### Añadir atributo sin setAttribute
Podemos utilizar el método normal de configuración de objetos para establecer un atributo, pero esto no puede funcionar para todos los elementos. Algunos atributos son propiedades de los objetos del DOM y se pueden establecer directamente. Por ejemplo, id y class
```js
//otra forma de establecer un atributo
titles[3].className = "title";
titles[3].id = "fourth-title";
```
#### Añadir una clase mediante classList
El método classList es un buen método para añadir clases adicionales. No anula la clase original si existe una clase, sino que añade una clase adicional para el elemento.
```js
//otra forma de establecer un atributo: anexar la clase, no se sobrepone a
titles[3].classList.add("title", "header-title");
```
#### Eliminación de la clase mediante remove
De forma similar a la adición, también podemos eliminar la clase de un elemento. Podemos eliminar una clase específica de un elemento.
```js
//otra forma de establecer un atributo: anexar la clase, no se sobrepone a
titles[3].classList.remove("title", "header-title");
```
### Añadir texto a un elemento HTML
Un HTML es un bloque compuesto por una etiqueta de apertura, una etiqueta de cierre y un contenido de texto. Podemos añadir un contenido de texto utilizando la propiedad _textContent_ o \*innerHTML.
#### Añadir contenido de texto usando textContent
La propiedad _textContent_ se utiliza para añadir texto a un elemento HTML.
```js
const titles = document.querySelectorAll("h1");
titles[3].textContent = "Fourth Title";
```
#### Añadir contenido de texto usando innerHTML
La mayoría de la gente se confunde entre _textContent_ y _innerHTML_. _textContent_ está pensado para añadir texto a un elemento HTML, sin embargo innerHTML puede añadir un elemento o elementos de texto o HTML como hijo.
##### textContent
Asignamos la propiedad del objeto HTML _textContent_ a un texto
```js
const titles = document.querySelectorAll("h1");
titles[3].textContent = "Fourth Title";
```
##### innerHTML
Usamos la propiedad innerHTML cuando queremos reemplazar o un contenido hijo completamente nuevo a un elemento padre.
El valor que asignemos será una cadena de elementos HTML.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript para todos:DOM</title>
</head>
<body>
<div class="wrapper">
<h1>Asabeneh Yetayeh desafíos en 2020</h1>
<h2>Reto 30DaysOfJavaScript</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 propiedad innerHTML puede permitirnos también eliminar todos los hijos de un elemento padre. En lugar de utilizar removeChild() yo recomendaría el siguiente método.
```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>
```
### Añadir estilo
#### Añadir estilo Color
Añadamos un poco de estilo a nuestros títulos. Si el elemento tiene índice par le damos color verde sino rojo.
```js
const titles = document.querySelectorAll("h1");
titles.forEach((title, i) => {
title.style.fontSize = "24px"; // todos los títulos tendrán un tamaño de letra de 24px
if (i % 2 === 0) {
title.style.color = "green";
} else {
title.style.color = "red";
}
});
```
#### Añadir estilo Background Color
Añadamos un poco de estilo a nuestros títulos. Si el elemento tiene índice par le damos color verde sino rojo.
```js
const titles = document.querySelectorAll("h1");
titles.forEach((title, i) => {
title.style.fontSize = "24px"; // todos los títulos tendrán un tamaño de letra de 24px
if (i % 2 === 0) {
title.style.backgroundColor = "green";
} else {
title.style.backgroundColor = "red";
}
});
```
#### Añadir estilo Font Size
Añadamos algo de estilo a nuestros títulos. Si el elemento tiene índice par le damos 20px sino 30px
```js
const titles = document.querySelectorAll("h1");
titles.forEach((title, i) => {
title.style.fontSize = "24px"; // todos los títulos tendrán un tamaño de letra de 24px
if (i % 2 === 0) {
title.style.fontSize = "20px";
} else {
title.style.fontSize = "30px";
}
});
```
Como has notado, las propiedades de css cuando lo usamos en JavaScript va a ser un camelCase. Las siguientes propiedades CSS cambian de background-color a backgroundColor, font-size a fontSize, font-family a fontFamily, margin-bottom a marginBottom.
---
🌕 Ahora, estás completamente dotado de un súper poder, has completado la parte más importante y desafiante del desafío y en general de JavaScript. Has aprendido DOM y ahora tienes la capacidad de construir y desarrollar aplicaciones. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
## Ejercicios
### Ejercicios: Nivel 1
1. Crear un archivo index.html y poner cuatro elementos p: Obtenga el primer párrafo utilizando **_document.querySelector(tagname)_** y el nombre de la etiqueta
2. Obtener cada uno de los párrafos usando **_document.querySelector('#id')_** mediante su id
3. Obtener todos los p como nodeList usando **_document.querySelectorAll(tagname)_** por su nombre de etiqueta
4. Recorrer nodeList y obtener el contenido del texto de cada párrafo
5. Establecer un textContent para el párrafo del cuarto párrafo,**_Fourth Paragraph_**
6. Establezca los atributos id y class para todos los párrafos utilizando diferentes métodos de establecimiento de atributos
### Ejercicios: Nivel 2
1. Cambiar el estilo de cada párrafo mediante JavaScript (ej, color, fondo, borde, tamaño de la fuente, familia de la fuente)
1. Seleccione todos los párrafos y haga un bucle a través de cada uno de los elementos y dé al primer y tercer párrafo un color verde, y al segundo y cuarto párrafo un color rojo
1. Establecer textContent, id y class a cada párrafo
### Ejercicios: Nivel 3
#### DOM: Mini proyecto 1
1. Desarrolle la siguiente aplicación, utilice los siguientes elementos HTML para empezar. Obtendrá el mismo código en la carpeta de inicio. Aplique todos los estilos y la funcionalidad utilizando sólo JavaScript.
- El color del año cambia cada 1 segundo
- El color de fondo de la fecha y la hora cambia cada dos segundos
- El reto completado tiene fondo verde
- El desafío en curso tiene fondo amarillo
- Los próximos retos tienen fondo rojo
```html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript para todos: DOM</title>
</head>
<body>
<div class="wrapper">
<h1>Asabeneh Yetayeh retos en 2020</h1>
<h2>Reto 30DaysOfJavaScript</h2>
<ul>
<li>Reto 30DaysOfPython Realizado</li>
<li>Reto 30DaysOfJavaScript en curso</li>
<li>Reto 30DaysOfReact próximamente</li>
<li>Reto 30DaysOfFullStack próximamente</li>
<li>Reto 30DaysOfDataAnalysis próximamente</li>
<li>Reto 30DaysOfReactNative próximamente</li>
<li>Reto 30DaysOfMachineLearning próximamente</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)
🎉 ¡FELICITACIONES! 🎉
[<< Día 20](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md) | [Día 22 >>](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md)

@ -0,0 +1,224 @@
<div align="center">
<h1> 30 Días de JavaScript: Manipulación del Objeto 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>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 21](../dia_21_DOM/dia_21_dom.md) | [Día 23 >>](../dia_23_Event_Listeners/dia_23_event_listeners.md)
![Thirty Days Of JavaScript](../images/banners/day_1_22.png)
- [Día 22](#día-22)
- [DOM(Document Object Model)-Día 2](#domdocument-object-model-día-2)
- [Creando un elemento](#creando-un-elemento)
- [Creación de elementos](#creación-de-elementos)
- [Añadir un hijo a un elemento padre](#añadir-un-hijo-a-un-elemento-padre)
- [Eliminar un elemento hijo de un nodo padre](#eliminar-un-elemento-hijo-de-un-nodo-padre)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
- [Ejercicios: Nivel 2](#ejercicios-nivel-2)
- [Ejercicios: Nivel 3](#ejercicios-nivel-3)
# Día 22
## DOM(Document Object Model)-Día 2
### Creando un elemento
Para crear un elemento HTML utilizamos el nombre de la etiqueta. La creación de un elemento HTML mediante JavaScript es muy sencilla y directa. Utilizamos el método _document.createElement()_. El método toma un nombre de etiqueta de elemento HTML como parámetro de cadena.
```js
// sintaxus
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>
```
### Creación de elementos
Para crear múltiples elementos debemos utilizar el bucle. Usando el bucle podemos crear tantos elementos HTML como queramos.
Después de crear el elemento podemos asignar valor a las diferentes propiedades del objeto 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>
```
### Añadir un hijo a un elemento padre
Para ver un elemento creado en el documento HTML debemos añadirlo al padre como elemento hijo. Podemos acceder al cuerpo del documento HTML utilizando _document.body_. El _document.body_ soporta el método _appendChild()_. Vea el ejemplo siguiente.
```html
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<script>
// creación de múltiples elementos y anexión al elemento padre
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>
```
### Eliminar un elemento hijo de un nodo padre
Después de crear un HTML, es posible que queramos eliminar uno o varios elementos y podemos utilizar el método _removeChild()_.
**Ejemplo:**
```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>
```
Como hemos visto en la sección anterior hay una forma mejor de eliminar todos los elementos HTML internos o hijos de un elemento padre utilizando el método _innerHTML_ propiedades.
```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>
```
El fragmento de código anterior borró todos los elementos hijos.
---
🌕 Eres muy especial, estás progresando cada día. Ahora, sabes cómo destruir un elemento DOM creado cuando es necesario. Aprendiste DOM y ahora tienes la capacidad de construir y desarrollar aplicaciones. Te quedan sólo ocho días para tu camino a la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
## Ejercicios
### Ejercicios: Nivel 1
1. Crear un div contenedor en el documento HTML y crear 100 a 100 números dinámicamente y anexar al div contenedor.
- El fondo de los números pares es verde
- El fondo de los números impares es amarillo
- El fondo de los números primos es rojo
![Number Generator](./../images/projects/dom_min_project_day_number_generators_2.1.png)
### Ejercicios: Nivel 2
1. Utilice el array de países para mostrar todos los países. Vea el diseño
![World Countries List](./../images/projects/dom_min_project_countries_aray_day_2.2.png)
### Ejercicios: Nivel 3
Compruebe los requisitos de este proyecto a partir de ambas imágenes (jpg y gif). Todos los datos y el CSS se han implementado utilizando únicamente JavaScript. Los datos se encuentran en la carpeta de inicio del proyecto\*3. El botón desplegable se ha creado utilizando el [details\*](https://www.w3schools.com/tags/tag_details.asp) elemento HTML.
![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)
🎉 ¡FELICITACIONES! 🎉
[<< Día 21](../dia_21_DOM/dia_21_dom.md) | [Día 23 >>](../dia_23_Event_Listeners/dia_23_event_listeners.md)

@ -0,0 +1,334 @@
<div align="center">
<h1> 30 Días de 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>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 22](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md) | [Día 24 >>](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md)
![Thirty Days Of JavaScript](../images/banners/day_1_23.png)
- [Día 23](#día-23)
- [DOM(Document Object Model)-Día 3](#domdocument-object-model-día-3)
- [Event Listeners](#event-listeners)
- [Click](#click)
- [Doble Click](#doble-click)
- [Mouse enter](#mouse-enter)
- [Obtener el valor de un elemento input](#obtener-el-valor-de-un-elemento-input)
- [valor de entrada](#valor-de-entrada)
- [evento de entrada y cambio](#evento-de-entrada-y-cambio)
- [evento de desenfoque](#evento-de-desenfoque)
- [keypress, keydow y keyup](#keypress-keydow-y-keyup)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
# Día 23
## DOM(Document Object Model)-Día 3
### Event Listeners
Eventos HTML comunes: onclick, onchange, onmouseover, onmouseout, onkeydown, onkeyup, onload.
Podemos añadir el método **event_listener** (escuchador de eventos) a cualquier objeto DOM. Utilizamos el método **_addEventListener()_** para escuchar diferentes tipos de eventos en los elementos HTML. El método _addEventListener()_ toma dos argumentos, un event listener y una función callback.
```js
selectedElement.addEventListener("eventlistner", function (e) {
// la actividad que quieres que ocurra después del evento estará aquí
});
// or
selectedElement.addEventListener("eventlistner", (e) => {
// la actividad que quieres que ocurra después del evento estará aquí
});
```
#### Click
Para adjuntar un event listener a un elemento, primero seleccionamos el elemento y luego adjuntamos el método addEventListener. El event listener toma como argumento el tipo de evento y las funciones de callback.
El siguiente es un ejemplo de evento de tipo click.
**Ejemplo: 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>
```
También se puede adjuntar un evento directamente al elemento HTML como script en línea.
**Ejemplo: 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>
```
#### Doble Click
Para adjuntar un event listener a un elemento, primero seleccionamos el elemento y luego adjuntamos el método addEventListener. El event listener toma como argumento el tipo de evento y las funciones de callback.
El siguiente es un ejemplo de evento de tipo click.
**Ejemplo: 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
Para adjuntar un event listener a un elemento, primero seleccionamos el elemento y luego adjuntamos el método addEventListener. El event listener toma como argumento el tipo de evento y las funciones de callback.
El siguiente es un ejemplo de evento de tipo click.
**Ejemplo: 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>
```
A estas alturas ya estás familiarizado con el método addEventListen y cómo añadir un event listener. Hay muchos tipos de event listeners. Pero en este reto nos centraremos en los eventos importantes más comunes.
Lista de eventos:
- click - cuando se hace click en el elemento
- dblclick - cuando se hace doble click en el elemento
- mouseenter - cuando el punto del mouse ingresa al elemento
- mouseleave - cuando el puntero del mouse abandona el elemento
- mousemove - cuando el puntero del mouse se mueve sobre el elemento
- mouseover - cuando el puntero del mouse se mueve sobre el elemento
- mouseout - cuando el puntero del mouse sale del elemento
- input - cuando el valor entra en el input de entrada
- change - cuando el valor cambia en el input de entrada
- blur - cuando el elemento no está enfocado
- keydown - cuando una tecla está pulsada
- keyup - cuando una tecla está levantada
- keypress - cuando pulsamos cualquier tecla
- onload - cuando el navegador ha terminado de cargar una página
Pruebe los tipos de eventos anteriores sustituyendo el tipo de evento en el fragmento de código anterior.
### Obtener el valor de un elemento input
Normalmente rellenamos formularios y los formularios aceptan datos. Los campos de los formularios se crean utilizando el elemento HTML input. Vamos a construir una pequeña aplicación que nos permita calcular el índice de masa corporal de una persona utilizando dos campos de entrada, un botón y una etiqueta p.
### valor de entrada
```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>
```
#### evento de entrada y cambio
En el ejemplo anterior, hemos conseguido obtener los valores de entrada de dos campos de entrada haciendo click en el botón. Qué tal si queremos obtener el valor sin hacer click en el botón. Podemos utilizar el tipo de evento _change_ o _input_ para obtener los datos inmediatamente del campo de entrada cuando el campo está en el foco. Veamos cómo lo haremos.
```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 de desenfoque
A diferencia de _input_ o _change_, el evento _blur_ se produce cuando el campo de entrada no está enfocado.
```js
<!DOCTYPE html>
<html>
<head>
<title>Document Object Model:30 Days Of JavaScript</title>
</head>
<body>
<h1>Giving feedback using blur event</h1>
<input type="text" id="mass" placeholder="say something" />
<p></p>
<script>
const input = document.querySelector('input')
const p = document.querySelector('p')
input.addEventListener('blur', (e) => {
p.textContent = 'Field is required'
p.style.color = 'red'
})
</script>
</body>
</html>
```
#### keypress, keydow y keyup
Podemos acceder a todos los números de teclas del teclado utilizando diferentes tipos de event listener. Usemos keypress y obtengamos el keyCode de cada tecla del teclado.
```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>
```
---
🌕 Eres muy especial, estás progresando cada día. Ahora, sabes cómo manejar cualquier tipo de eventos DOM. . Te quedan sólo siete días para tu camino a la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos.
## Ejercicios
### Ejercicios: Nivel 1
1. Generar números y marcar pares, impares y primos con tres colores diferentes. Vea la imagen de abajo.
![Number Generator](./../images/projects/dom_min_project_number_generator_day_3.1.gif)
1. Generando el código del teclado usando even listener. La imagen de abajo.
![Keyboard key](./../images/projects/dom_min_project_keycode_day_3.2.gif)
🎉 ¡FELICITACIONES! 🎉
[<< Día 22](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md) | [Día 24 >>](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md)

@ -0,0 +1,37 @@
<div align="center">
<h1> 30 Días de JavaScript: Mini Proyecto Sistema Solar</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 23](../dia_23_Event_Listeners/dia_23_event_listeners.md) | [Día 25 >>](../dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md)
![Thirty Days Of JavaScript](../images/banners/day_1_24.png)
- [Día 24](#día-24)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
# Día 24
## Ejercicios
### Ejercicios: Nivel 1
1. Desarrollar una pequeña aplicación que calcule el peso de un objeto en un determinado planeta. La imagen gif no está completa revisa el video en el archivo de inicio.
![Solar System](./../images/projects/dom_min_project_solar_system_day_4.1.gif)
🎉 ¡FELICITACIONES! 🎉
[<< Día 23](../dia_23_Event_Listeners/dia_23_event_listeners.md) | [Día 25 >>](../dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md)

@ -0,0 +1,39 @@
<div align="center">
<h1> 30 Días de JavaScript: Visualización de Datos de los Países del Mundo</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 24](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md) | [Día 26 >>](../dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md)
![Thirty Days Of JavaScript](../images/banners/day_1_25.png)
- [Día 25](#día-25)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
# Día 25
## Ejercicios
### Ejercicios: Nivel 1
1. Visualiza los diez países más poblados y los diez idiomas más hablados del mundo usando 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)
🎉 ¡FELICITACIONES! 🎉
[<< Día 24](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md) | [Día 26 >>](../dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md)

@ -0,0 +1,37 @@
<div align="center">
<h1> 30 Días de JavaScript: Visualización de Datos de los Países del Mundo 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>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 25](../dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md) | [Día 27 >>](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md)
![Thirty Days Of JavaScript](../images/banners/day_1_26.png)
- [Día 26](#día-26)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
# Día 26
## Ejercicios
### Ejercicios: Nivel 1
1. Visualice el array de países de la siguiente manera
![Motivation](./../images/projects/dom_mini_project_countries_day_6.1.gif)
🎉 ¡FELICITACIONES! 🎉
[<< Día 25](../dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md) | [Día 27 >>](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md)

@ -0,0 +1,37 @@
<div align="center">
<h1> 30 Días de JavaScript: Portafolio</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 26](../dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md) | [Día 28 >>](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md)
![Thirty Days Of JavaScript](../images/banners/day_1_27.png)
- [Día 27](#día-27)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
# Día 27
## Ejercicios
### Ejercicios: Nivel 1
1. Crea lo siguiente usando HTML, CSS y JavaScript
![Slider](./../images/projects/dom_mini_project_slider_day_7.1.gif)
🎉 ¡FELICITACIONES! 🎉
[<< Día 26](../dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md) | [Día 28 >>](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md)

@ -0,0 +1,37 @@
<div align="center">
<h1> 30 Días de JavaScript: Tabla de Posiciones</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 27](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md) | [Día 29>>](../dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md)
![Thirty Days Of JavaScript](../images/banners/day_1_28.png)
- [Día 28](#día-28)
- [Ejercicio](#ejercicio)
- [Ejercicio: Nivel 1](#ejercicio-nivel-1)
# Día 28
## Ejercicio
### Ejercicio: Nivel 1
1. Crea lo siguiente usando HTML, CSS y JavaScript
![Slider](./../images/projects/dom_mini_project_leaderboard_day_8.1.gif)
🎉 ¡FELICITACIONES! 🎉
[<< Día 27](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md) | [Día 29>>](../dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md)

@ -0,0 +1,37 @@
<div align="center">
<h1> 30 Días de JavaScript: Animación de Caracteres</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
[<< Día 28](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md) | [Día 30>>](../dia_30_Mini_Proyecto_Final/dia_30_mini_proyecto_final.md)
![Thirty Days Of JavaScript](../images/banners/day_1_29.png)
- [Día 29](#día-29)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
# Día 29
## Ejercicios
### Ejercicios: Nivel 1
1. Crea la siguiente animación utilizando (HTML, CSS, JS)
![Slider](./../images/projects/dom_min_project_30DaysOfJavaScript_color_changing_day_9.1.gif)
🎉 ¡FELICITACIONES! 🎉
[<< Día 28](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md) | [Día 30>>](../dia_30_Mini_Proyecto_Final/dia_30_mini_proyecto_final.md)

@ -0,0 +1,67 @@
<div align="center">
<h1> 30 Días de JavaScript: Proyecto Final</h1>
<a class="header-badge" target="_blank" href="https://www.linkedin.com/in/asabeneh/">
<img src="https://img.shields.io/badge/style--5eba00.svg?label=LinkedIn&logo=linkedin&style=social">
</a>
<a class="header-badge" target="_blank" href="https://twitter.com/Asabeneh">
<img alt="Twitter Follow" src="https://img.shields.io/twitter/follow/asabeneh?style=social">
</a>
<sub>Autor:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> Enero, 2020</small>
</sub>
</div>
</div>
<div>
</div>
<div>
<small>Apoya al <strong>autor</strong> para que cree más material educativo</small> <br />
<a href = "https://www.paypal.me/asabeneh"><img src='../../images/paypal_lg.png' alt='Paypal Logo' style="width:10%"/></a>
</div>
[<< Día 29](../dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md)
![Thirty Days Of JavaScript](../images/banners/day_1_30.png)
- [Día 30](#día-30)
- [Ejercicios](#ejercicios)
- [Ejercicios: Nivel 1](#ejercicios-nivel-1)
- [Testimonio](#testimonio)
- [Apoyo](#apoyo)
# Día 30
## Ejercicios
### Ejercicios: Nivel 1
1. Crea la siguiente animación utilizando (HTML, CSS, JS)
![Countries data](./../images/projects/dom_mini_project_countries_object_day_10.1.gif)
2. Valide el siguiente formulario utilizando 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)
🌕 Tu viaje a la grandeza se ha completado con éxito. Has alcanzado un alto nivel de genialidad. Ahora, eres mucho más brillante que antes. Yo sabía lo que se necesita para llegar a este nivel y tú llegaste a este punto. Eres un verdadero héroe. Ahora, es el momento de celebrar tu éxito con un amigo o con la familia. Estoy deseando verte en otro reto.
## Testimonio
Ahora es el momento de apoyar al autor y expresar su opinión sobre el autor y 30DaysOfJavaScript. Puedes dejar tu testimonio en este [link](https://testimonify.herokuapp.com/)
## Apoyo
Puedes apoyar al autor para que produzca más material educativo
[![paypal](../../images/paypal_lg.png)](https://www.paypal.me/asabeneh)
![Congratulations](../../images/projects/congratulations.gif)
[<< Día 29](../dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.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>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
</div>
[<< Gün 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Gün 15>>](../15_Day_Classes/15_day_classes.md)
![Thirty Days Of JavaScript](../../images/banners/day_1_14.png)
- [Gün 14](#day-14)
- [Error Handling](#error-handling)
- [Error Types](#error-types)
- [Exercises](#exercises)
- [Exercises:Level 1](#exerciseslevel-1)
- [Exercises: Level 2](#exercises-level-2)
- [Exercises:Level](#exerciseslevel)
# Gün 14
## Error Handling
JavaScript geniş yazılmış bir dildir. Bazı zamanlar, tanımsız bir değişkene erişmeye veya tanımsız bir işlevi çağırmaya çalıştığınızda bir çalışma zamanı hatası alırsınız.
JavaScript, Python veya Java'ya benzer, try-catch-finally bloğunu kullanarak çalışma zamanı hatalarını yakalamak için bir hata işleme mekanizması sağlar.
```js
try {
// hata verilebilicek kod
} catch (err) {
// bir hata oluşursa çalıştırılacak kod
} finally {
// bir hatanın oluşup oluşmadığına bakılmaksızın yürütülecek kod
}
```
**try**: try bloğunda hata oluşturabilecek kodu yazın. try ifadesi, yürütülürken hatalar için test edilecek bir kod bloğu tanımlamamızı sağlar.
**catch**: Bir hata oluştuğunda catch bloğunda bir şeyler yapmak için kod yazın. Catch bloğu, size hata bilgisi verecek parametrelere sahip olabilir. Yakalama bloğu, bir hatayı günlüğe kaydetmek veya kullanıcıya belirli mesajları görüntülemek için kullanılır.
**finally**: finally bloğu, bir hata oluşmasından bağımsız olarak her zaman yürütülür. finally bloğu, kalan görevi tamamlamak veya try bloğunda hata oluşmadan önce değişmiş olabilecek değişkenleri sıfırlamak için kullanılabilir.
**Örnek:**
```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
```
Catch bloğu bir parametre alır. Catch bloğuna parametre olarak e, err veya error iletmek yaygındır. Bu parametre bir nesnedir ve isim ve mesaj anahtarlarına sahiptir. Adı ve mesajı kullanalım.
```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: throw ifadesi özel bir hata oluşturmamıza izin verir. Bir dize, sayı, boolean veya bir nesne aracılığıyla yapabiliriz. Bir istisna atmak için throw ifadesini kullanın. Bir throw exception yazdığınızda, expression specifies değerini belirtir. Aşağıdakilerin her biri throw exception atar:
```js
throw 'Error2' // generates an exception with a string value
throw 42 // generates an exception with the value 42
throw true // generates an exception with the value true
throw new Error('Required') // generates an error object with the message of Required
```
```js
const throwErrorExampleFun = () => {
let message
let x = prompt('Enter a number: ')
try {
if (x == '') throw 'empty'
if (isNaN(x)) throw 'not a number'
x = Number(x)
if (x < 5) throw 'too low'
if (x > 10) throw 'too high'
} catch (err) {
console.log(err)
}
}
throwErrorExampleFun()
```
### Error Types
- ReferenceError: Geçersiz bir referans oluşturur. Tanımlanmamış bir değişken kullanırsak bir ReferenceError atılır.
```js
let firstName = 'Asabeneh'
let fullName = firstName + ' ' + lastName
console.log(fullName)
```
```sh
Uncaught ReferenceError: lastName is not defined
at <anonymous>:2:35
```
- SyntaxError: Bir syntax(sözdizim) hatası oluşturur.
```js
let square = 2 x 2
console.log(square)
console.log('Hello, world")
```
```sh
Uncaught SyntaxError: Unexpected identifier
```
- TypeError: Bir type hatası oluşturur
```js
let num = 10
console.log(num.toLowerCase())
```
```sh
Uncaught TypeError: num.toLowerCase is not a function
at <anonymous>:2:17
```
Bunlar, kod yazarken karşılaşabileceğiniz yaygın hatalardan bazılarıdır. Hataları anlamak, hangi hataları yaptığınızı bilmenize yardımcı olabilir ve kodunuzda hızlı bir şekilde hata ayıklamanıza yardımcı olur.
🌕 Kusursuzsun. Artık hataların nasıl ele alınacağını biliyorsunuz ve beklenmeyen kullanıcı girdilerini işleyen sağlam bir uygulama yazabilirsiniz. 14. gün zorluklarını yeni tamamladınız ve mükemmelliğe giden yolda 14 adım öndesiniz. Şimdi beyniniz ve kasınız için bazı egzersizler yapın.
## Egzersizler
### Egzersiz:Seviye 1
Pratik
### Egzersiz: Seviye 2
Pratik
### Egzersiz: Seviye 3
Pratik
🎉 TEBRİKLER ! 🎉
[<< Gün 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Gün 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>Author:
<a href="https://www.linkedin.com/in/asabeneh/" target="_blank">Asabeneh Yetayeh</a><br>
<small> January, 2020</small>
</sub>
</div>
[<< Gün 14](../14_Day_Error_handling/14_day_error_handling.md) | [Gün 16>>](../16_Day_JSON/16_day_json.md)
![Thirty Days Of JavaScript](../../images/banners/day_1_15.png)
- [Gün 15](#gün-15)
- [Sınıflar](#sınıflar)
- [Sınıfın Tanımı ](#defining-a-classes)
- [Sınıf Örneklemesi](#class-instantiation)
- [Sınıf Oluşturucu](#class-constructor)
- [Constructor ile varsayılan değerler](#default-values-with-constructor)
- [Sınıf methodları](#class-methods)
- [Başlangıç değeri olan özellikler](#properties-with-initial-value)
- [getter](#getter)
- [setter](#setter)
- [Statik method](#static-method)
- [Inheritance](#inheritance)
- [Overriding methods](#overriding-methods)
- [Egzersizler](#egzersizler)
- [Egzersiz Seviye 1](#egzersizler-seviye-1)
- [Egzersiz Seviye 2](#egzersizler-seviye-2)
- [Egzersiz Seviye 3](#egzersizler-seviye-3)
# Gün 15
## Sınıflar - Classes
JavaScript nesne tabanlı progralama dilidir. JavaScript'teki her şey, özellikleri ve yöntemleriyle bir nesnedir. Nesne oluşturmak için sınıf oluşturutuz. Sınıflar nesne oluşturucu (constructor) gibidir yada nesne oluşturmak için taslak gibidir. Nesne oluşturmak için sınıf oluştururuz. Sınıf, nesnenin niteliklerini ve davranışını tanımlarken, nesne ise sınıfı temsil eder.
Bir sınıf oluşturduğumuzda, istediğimiz zaman ondan nesne oluşturabiliriz. Bir sınıftan nesne oluşturmaya class instantiation(sınıf başlatma) denir.
Nesne bölümünde, bir nesne değişmezinin nasıl oluşturulacağını gördük. Nesne değişmezi bir singleton'dur. Benzer bir nesne elde etmek istiyorsak, onu yazmalıyız. Ancak sınıf, birçok nesne oluşturmaya izin verir. Bu, kod miktarını ve kod tekrarını azaltmaya yardımcı olur.
### Sınıfın Tanımı ( Instantiation )
JavaScript'te bir sınıf tanımlamak için class anahtar kelimesine, **CamelCase**'de bir sınıfın adına ve blok koduna (iki küme parantez) ihtiyacımız var. Kişi adında bir sınıf oluşturalım.
```sh
// syntax
class ClassName {
// code goes here
}
```
**Örnek:**
```js
class Person {
// code goes here
}
```
Person sınıfı oluşturduk fakat içine bir şey yazmadık.
### Sınıf Örneklemesi
Örnekleme sınıfı, bir sınıftan bir nesne oluşturmak anlamına gelir. _new_ anahtar kelimesine ihtiyacımız var ve sınıfın adını _new_ kelimesinden sonra çağırıyoruz.
Person sınıfımız içerisine dog nesnesi oluşturalım.
```js
class Person {
// code goes here
}
const person = new Person()
console.log(person)
```
```sh
Person {}
```
Gördüğünüz gibi bir Person nesnesi oluşturduk. Sınıfın henüz herhangi bir özelliği olmadığı için nesne de boştur.
Sınıfta farklı özellikler iletmek için class constructor(sınıf yapıcısını) kullanalım.
### Sınıf Oluşturucu ( Constructor )
Constructor, nesnemiz için bir taslak oluşturmamıza izin veren yerleşik bir fonksiyondur. Constructor fonksiyonu, constructor anahtar sözcüğü ile başlar ve ardından bir parantez gelir. Parantez içinde nesnenin özelliklerini parametre olarak iletiyoruz. Bu anahtar sözcüğü, constructor parametrelerini sınıfa eklemek için kullanırız.
Aşağıdaki Person sınıfı oluşturucusu firstName ve lastName özelliği oluşturur. Bu özellikler, _this_ anahtar kelimesi kullanılarak Person sınıfına eklenir. _this_ sınıfın kendinisi ifade eder.
```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}
```
Nesnenin tüm anahtarları tanımsızdır(undefined). Ne zaman somutlaştırsak, özelliklerin değerini geçmeliyiz. Sınıfı somutlaştırdığımızda şu anda değeri iletelim.
```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"}
```
En başta da belirttiğimiz gibi bir sınıf oluşturduğumuzda, sınıfı kullanarak birçok nesne oluşturabiliriz. Şimdi, Person sınıfını kullanarak birden fazla kişi nesnesi oluşturalım.
```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"}
```
Person sınıfını kullanarak 3 kişi nesnesi oluşturduk. Gördüğünüz gibi sınıfımızda çok fazla özellik yok,hadi biraz daha sınıfımızın içerisine özellik ekleyelim.
```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"}
```
### Constructor ile varsayılan değerler
Constructor fonksiyonun özellikleri,diğer normal fonksiyonlar gibi bir değere sahip olabilir.
```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"}
```
### Sınıf methodları
Bir sınıfın içindeki constructor, nesne için bir tasklak oluşturmamıza izin veren yerleşik bir fonksiyondur. Bir sınıfta sınıf methodları oluşturabiliriz. Methodlar, sınıf içindeki JavaScript fonksiyonlarıdır. Bazı sınıf methodları oluşturalım.
```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
```
### Başlangıç değeri olan özellikler
Bazı özellikler için bir sınıf oluşturduğumuzda bir başlangıç değerine sahip olabiliriz. Örneğin bir oyun oynuyorsanız, başlama puanınız sıfır olacaktır. Yani, sıfır olan bir başlangıç puanımız veya herhangi bir puanımız olabilir. Diğer bir şekilde, bir başlangıç becerisine sahip olabiliriz ve bir süre sonra biraz beceri kazanacağız.
```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
[]
[]
```
Bir method regular , getter yada setter olabilir. getter ve setter yakından inceleyelim.
### getter
get yöntemi, nesneden değere erişmemizi sağlar. Get anahtar sözcüğünü ve ardından bir fonksiyon kullanarak bir get methodu yazıyoruz. Özelliklere doğrudan nesneden erişmek yerine değeri almak için getter kullanırız. Aşağıdaki örneğe bakalım
```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
Setter yöntemi, belirli özelliklerin değerini değiştirmemize izin verir. _set_ anahtar kelimesini kullanarak bir fonksiyon kullanarak bir setter methodu yazıyoruz. Aşağıdaki örneğe bakalım.
```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"]
```
Regular(normal) method ile getter arasındaki fark sizi şaşırtmasın. Normal bir method yapmayı biliyorsanız, iyisiniz. Person sınıfına getPersonInfo adlı normal method ekleyelim.
```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.
```
### Statik method
Statik anahtar kelime, bir sınıf için statik bir yöntem tanımlar. Statik methodlar, sınıfın örneklerinde(instance) çağrılmaz. Bunun yerine, sınıfın kendisinde çağrılırlar. Bunlar genellikle nesneler oluşturma veya klonlama fonskiyonları gibi yardımcı fonksiyonlardır. Statik methoda bir örnek _Date.now()_'dur. _now_ yöntemi doğrudan sınıftan çağrılır.
```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
```
Statik methodlar, yardımcı fonksiyonlar olarak kullanılabilen yöntemlerdir.
## Inheritance (Kalıtım)
Inheritance kullanarak ana sınıfın tüm özelliklerine ve yöntemlerine erişebiliriz. Bu, kod tekrarını azaltır. Hatırlarsanız, bir Person ana sınıfımız var ve ondan alt sınıflar yaratacağız. Alt sınıfımız öğrenci, öğretmen vb. olabilir.
```js
// syntax
class ChildClassName extends {
// code goes here
}
```
Person ebeveyn sınıfından bir Student alt sınıfı oluşturalım.
```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.
```
### Overriding method
Gördüğünüz gibi Person Class'taki tüm yöntemlere erişmeyi başardık ve Student alt sınıfında kullandık. Ana yöntemlerini özelleştirebiliriz, bir alt sınıfa ek özellikler ekleyebiliriz. Özelleştirmek istiyorsak, methodlar ve ekstra özellikler eklemek istiyorsak, alt sınıfa için constructor fonksiyonu kullanmamız gerekir. Constructor işlevinin içinde, üst sınıftan tüm özelliklere erişmek için super() işlevini çağırırız. Person sınıfının cinsiyeti yoktu ama şimdi öğrenci sınıfı için cinsiyet özelliğini verelim. Alt sınıfta aynı method adı kullanılıyorsa, üst yöntem geçersiz kılınır.
```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
```
Şimdi, getPersonInfo methodu geçersiz kılındı ve kişinin erkek mi yoksa kadın mı olduğunu tanımlar.
🌕 Sen mükemmelsin. Artık sınıf oluşturmayı biliyorsunuz ve her şeyi bir nesneye dönüştürme gücünüz var. Büyüklüğe giden yolun yarısına kadar geldin. Şimdi beyniniz ve kasınız için bazı egzersizler yapın.
## Egzersizler
### Egzersiz Seviye 1
1. Bir Animal sınıfı oluşturun. Sınıf, isim, yaş, renk, ayak sayısı özelliklerine sahip olacak ve farklı yöntemler oluşturacaktır
2. Animal sınıfına Dog ve Cat adı altında alt sınıflar oluşturun
### Egzersiz Seviye 2
1. Oluşturduğunuz Animal sınıfını override methoduyla yazın
### Egzersiz Seviye 3
1. Bir örneğin merkezi eğilim ölçüsünü (ortalama, medyan, mod) ve değişkenlik ölçüsünü (aralık, varyans, standart sapma) hesaplayan bir program geliştirmeye çalışalım. Bu ölçülere ek olarak, numunenin min, maks, sayım, yüzdelik ve frekans dağılımını bulun. İstatistikler adlı bir sınıf oluşturabilir ve İstatistik sınıfı için yöntem olarak istatistiksel hesaplamalar yapan tüm işlevleri oluşturabilirsiniz. Aşağıdaki çıktıyı kontrol edin.
```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. PersonAccount adlı bir sınıf oluşturun. ad, soyad, gelirler, giderler özelliklerine sahip olan totalIncome, totalExpense, accountInfo,addIncome, addExpense ve accountBalance methodlarına sahip.
🎉 TEBRİKLER ! 🎉
[<< Gün 14](../14_Day_Error_handling/14_day_error_handling.md) | [Gün 16>>](../16_Day_JSON/16_day_json.md)
Loading…
Cancel
Save