From b7574bd596835e31279074cbb4fccc4b9a3b37c5 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 18 Sep 2022 21:34:13 -0500 Subject: [PATCH 01/26] Spanish translation day 15 of 30 --- .../dia_14_manejo_de_errores.md | 4 +- Spanish/dia_15_Clases/dia_15_clases.md | 715 ++++++++++++++++++ 2 files changed, 717 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_15_Clases/dia_15_clases.md diff --git a/Spanish/dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md b/Spanish/dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md index 70ec130..973c180 100644 --- a/Spanish/dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md +++ b/Spanish/dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md @@ -14,7 +14,7 @@ -[<< Día 13](../dia_13_Metodos_del_Objeto_Console/dia_13_metodos_del_objeto_console.md) | [Día 15>>](..) +[<< Día 13](../dia_13_Metodos_del_Objeto_Console/dia_13_metodos_del_objeto_console.md) | [Día 15>>](../dia_15_Clases/dia_15_clases.md) ![Thirty Days Of JavaScript](../images/banners/day_1_14.png) @@ -190,4 +190,4 @@ Practica 🎉 ¡FELICITACIONES! 🎉 -[<< Día 13](../dia_13_Metodos_del_Objeto_Console/dia_13_metodos_del_objeto_console.md) | [Día 15>>](..) +[<< Día 13](../dia_13_Metodos_del_Objeto_Console/dia_13_metodos_del_objeto_console.md) | [Día 15>>](../dia_15_Clases/dia_15_clases.md) diff --git a/Spanish/dia_15_Clases/dia_15_clases.md b/Spanish/dia_15_Clases/dia_15_clases.md new file mode 100644 index 0000000..f7134d7 --- /dev/null +++ b/Spanish/dia_15_Clases/dia_15_clases.md @@ -0,0 +1,715 @@ +
+

30 Días de JavaScript: Clases

+ + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
+ Enero, 2020 +
+ +
+ +[<< Día 14](../dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md) | [Día 16>>](..) + +![Thirty Days Of JavaScript](../images/banners/day_1_15.png) + +- [Día 15](#día-15) + - [Clases](#clases) + - [Definir una clase](#definir-una-clase) + - [Instanciar Clases](#instanciar-clases) + - [Constructor](#constructor) + - [Valores por defecto con el constructor](#valores-por-defecto-con-el-constructor) + - [Métodos de clase](#métodos-de-clase) + - [Propiedades con valor inicial](#propiedades-con-valor-inicial) + - [getter](#getter) + - [setter](#setter) + - [Método Static](#método-static) + - [Herencia](#herencia) + - [Anulación de métodos](#anulación-de-métodos) + - [Ejercicios](#ejercicios) + - [Ejercicios Nivel 1](#ejercicios-nivel-1) + - [Ejercicios Nivel 2](#ejercicios-nivel-2) + - [Ejercicios Nivel 3](#ejercicios-nivel-3) + +# Día 15 + +## Clases + +JavaScript es un lenguaje de programación orientado a objetos. Todo en JavScript es un objeto, con sus propiedades y métodos. Creamos una clase para crear un objeto. Una clase es como un constructor de objetos, o un "plano" para crear objetos. Instanciamos una clase para crear un objeto. La clase define los atributos y el comportamiento del objeto, mientras que el objeto, por su parte, representa la clase. + +Una vez que creamos una clase podemos crear un objeto a partir de ella cuando queramos. La creación de un objeto a partir de una clase se denomina instanciación de la clase. + +En la sección de objetos, vimos cómo crear un objeto literal. El objeto literal es un singleton (instancia única). Si queremos obtener un objeto similar, tenemos que escribirlo. Sin embargo, la clase permite crear muchos objetos. Esto ayuda a reducir la cantidad de código y la repetición del mismo. + +### Definir una clase + +Para definir una clase en JavaScript necesitamos la palabra clave _class_ , el nombre de una clase en **CamelCase** y bloque de código (dentro de dos corchetes). Vamos a crear una clase llamada Persona. + +```sh +// sintaxis +class ClassName { + // el código va aquí +} + +``` + +**Ejemplo:** + +```js +class Person { + // el código va aquí +} +``` + +Hemos creado una clase Persona pero no tiene nada dentro. + +### Instanciar Clases + +Instanciar una clase significa crear un objeto a partir de una clase. Necesitamos la palabra clave _new_ y llamamos al nombre de la clase después de la palabra _new_. + +Vamos a crear un objeto persona a partir de nuestra clase Persona. + +```js +class Person { + // el código va aquí +} +const person = new Person(); +console.log(person); +``` + +```sh +Person {} +``` + +Como puedes ver, hemos creado un objeto persona. Como la clase aún no tiene propiedades, el objeto también está vacío. + +Usemos el constructor de la clase para pasar diferentes propiedades a la clase. + +### Constructor + +El constructor es una función incorporada que permite crear un blueprint para nuestro objeto. La función constructora comienza con la palabra clave _constructor_ seguida de un paréntesis. Dentro del paréntesis pasamos las propiedades del objeto como parámetro. Utilizamos la palabra clave _this_ para adjuntar los parámetros del constructor con la clase. + +El siguiente constructor de la clase Persona tiene las propiedades firstName y lastName. Estas propiedades se adjuntan a la clase Persona utilizando la palabra clave _this_. _this_ se refiere a la propia clase. + +```js +class Person { + constructor(firstName, lastName) { + console.log(this); // Compruebe el resultado desde aquí + this.firstName = firstName; + this.lastName = lastName; + } +} + +const person = new Person(); + +console.log(person); +``` + +```sh +Person {firstName: undefined, lastName:undefined} +``` + +Todas las claves del objeto son undefined. Siempre que instanciemos debemos pasar el valor de las propiedades. Pasemos el valor en este momento cuando instanciamos la clase. + +```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"} +``` + +Como hemos dicho al principio, una vez que creamos una clase podemos crear muchos objetos utilizando la clase. Ahora, vamos a crear muchos objetos persona utilizando la clase Persona. + +```js +class Person { + constructor(firstName, lastName) { + console.log(this); // Compruebe el resultado desde aquí + 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"} +``` + +Usando la clase Persona creamos tres objetos persona. Como puedes ver nuestra clase no tenía muchas propiedades vamos a añadir más propiedades a la clase. + +```js +class Person { + constructor(firstName, lastName, age, country, city) { + console.log(this); // Compruebe el resultado desde aquí + 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"} +``` + +### Valores por defecto con el constructor + +Las propiedades de la función constructora pueden tener un valor por defecto como otras funciones regulares. + +```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(); // tomará el valor por defecto 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"} +``` + +### Métodos de clase + +El constructor dentro de una clase es una función incorporada que nos permite crear un blueprint para el objeto. En una clase podemos crear métodos de clase. Los métodos son funciones de JavaScript dentro de la clase. Vamos a crear algunos métodos de clase. + +```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 +``` + +### Propiedades con valor inicial + +Cuando creamos una clase para algunas propiedades podemos tener un valor inicial. Por ejemplo, si estás jugando una partida, tu puntuación inicial será cero. Así, podemos tener una puntuación inicial o una puntuación que sea cero. De otra manera, podemos tener una habilidad inicial y adquiriremos alguna habilidad después de algún tiempo. + +```js +class Person { + constructor(firstName, lastName, age, country, city) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + this.country = country; + this.city = city; + this.score = 0; + this.skills = []; + } + getFullName() { + const fullName = this.firstName + " " + this.lastName; + return fullName; + } +} + +const person1 = new Person("Asabeneh", "Yetayeh", 250, "Finland", "Helsinki"); +const person2 = new Person("Lidiya", "Tekle", 28, "Finland", "Espoo"); + +console.log(person1.score); +console.log(person2.score); + +console.log(person1.skills); +console.log(person2.skills); +``` + +```sh +0 +0 +[] +[] +``` + +Un método puede ser un método regular o un getter o un setter. Veamos, getter y setter. + +### getter + +El método get nos permite acceder al valor del objeto. Escribimos un método get utilizando la palabra clave _get_ seguida de una función. En lugar de acceder a las propiedades directamente desde el objeto utilizamos getter para obtener el valor. Vea el ejemplo siguiente + +```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); // No necesitamos paréntesis para llamar a un método getter +console.log(person2.getScore); + +console.log(person1.getSkills); +console.log(person2.getSkills); +``` + +```sh +0 +0 +[] +[] +``` + +### setter + +El método setter nos permite modificar el valor de ciertas propiedades. Escribimos un método setter utilizando la palabra clave _set_ seguida de una función. Vea el ejemplo de abajo. + +```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"] +``` + +No te confundas con la diferencia entre un método regular y un getter. If you know how to make a regular method you are good. Let us add regular method called getPersonInfo in the Person class. + +```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. +``` + +### Método Static + +La palabra clave static define un método estático para una clase. Los métodos estáticos no se llaman en las instancias de la clase. En cambio, se llaman en la propia clase. A menudo se trata de funciones de utilidad, como las funciones para crear o clonar objetos. Un ejemplo de método estático es _Date.now()_. El método _now_ se llama directamente desde la clase. + +```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 +``` + +Los métodos estáticos son métodos que pueden ser utilizados como funciones de utilidad. + +## Herencia + +Utilizando la herencia podemos acceder a todas las propiedades y métodos de la clase padre. Esto reduce la repetición de código. Si recuerdas, tenemos una clase padre Persona y crearemos hijos a partir de ella. Nuestra clase de niños podría ser estudiante, enseñar, etc. + +```js +// sintaxis +class ChildClassName extends { + // el código va aquí +} +``` + +Vamos a crear una clase hija Student a partir de la clase padre Person. + +```js +class Student extends Person { + saySomething() { + console.log("I am a child of the person class"); + } +} + +const s1 = new Student("Asabeneh", "Yetayeh", "Finland", 250, "Helsinki"); +console.log(s1); +console.log(s1.saySomething()); +console.log(s1.getFullName()); +console.log(s1.getPersonInfo()); +``` + +```sh +Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …} +I am a child of the person class +Asabeneh Yetayeh +Student {firstName: "Asabeneh", lastName: "Yetayeh", age: "Finland", country: 250, city: "Helsinki", …} +Asabeneh Yetayeh is Finland. He lives Helsinki, 250. +``` + +### Anulación de métodos + +Como puedes ver, conseguimos acceder a todos los métodos de la clase Persona y lo utilizamos en la clase hija Student. Podemos personalizar los métodos padre, podemos añadir propiedades adicionales a una clase hija. Si queremos personalizar, los métodos y si queremos añadir propiedades extra, necesitamos usar la función del constructor la clase hija también. Dentro de la función constructora llamamos a la función super() para acceder a todas las propiedades de la clase padre. La clase Persona no tenía género pero ahora vamos a dar la propiedad género para la clase hija, Student. Si se utiliza el mismo nombre de método en la clase hija, se anulará el método padre. + +```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 +``` + +Ahora, el método getPersonInfo ha sido anulado e identifica si la persona es hombre o mujer. + +🌕 Eres excelente. Ahora, usted conoce las clases y tiene el poder de convertir todo en un objeto. Has llegado a la mitad de tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tu músculo. + +## Ejercicios + +### Ejercicios Nivel 1 + +1. Crea una clase de Animal. La clase tendrá propiedades de nombre, edad, color, piernas y creará diferentes métodos. +2. Cree una clase hijo de Perro y Gato a partir de la Clase Animal. + +### Ejercicios Nivel 2 + +1. Sobrescribir el método que se crea en la clase Animal. + +### Ejercicios Nivel 3 + +1. Intentemos desarrollar un programa que calcule la medida de tendencia central de una muestra (media, mediana, moda) y la medida de variabilidad (rango, variación, desviación estándar). Además de esas medidas, encuentre el mínimo, el máximo, el recuento, el porcentaje y la distribución de frecuencias de la muestra. Puedes crear una clase llamada Statistics y crear todas las funciones que hacen cálculos estadísticos como método para la clase Statistics. Comprueba el resultado que aparece a continuación. + +```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 +// el resultado debería ser el siguiente +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. Crea una clase llamada PersonAccount. Tiene propiedades de nombre, apellido, ingresos, gastos y tiene métodos 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 y su descripción. + +🎉 ¡FELICITACIONES! 🎉 + +[<< Día 14](../dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md) | [Día 16>>](..) From a2c3ab672316e4e0a98312b34349c690181c8de7 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 18 Sep 2022 23:26:10 -0500 Subject: [PATCH 02/26] Spanish translation day 16 of 30 --- Spanish/dia_15_Clases/dia_15_clases.md | 4 +- Spanish/dia_16_JSON/dia_16_json.md | 602 +++++++++++++++++++++++++ 2 files changed, 604 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_16_JSON/dia_16_json.md diff --git a/Spanish/dia_15_Clases/dia_15_clases.md b/Spanish/dia_15_Clases/dia_15_clases.md index f7134d7..d0f0cb1 100644 --- a/Spanish/dia_15_Clases/dia_15_clases.md +++ b/Spanish/dia_15_Clases/dia_15_clases.md @@ -14,7 +14,7 @@ -[<< Día 14](../dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md) | [Día 16>>](..) +[<< Día 14](../dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md) | [Día 16>>](../dia_16_JSON/dia_16_json.md) ![Thirty Days Of JavaScript](../images/banners/day_1_15.png) @@ -712,4 +712,4 @@ Frequency Distribution: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34 🎉 ¡FELICITACIONES! 🎉 -[<< Día 14](../dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md) | [Día 16>>](..) +[<< Día 14](../dia_14_Manejo_de_Errores/dia_14_manejo_de_errores.md) | [Día 16>>](../dia_16_JSON/dia_16_json.md) diff --git a/Spanish/dia_16_JSON/dia_16_json.md b/Spanish/dia_16_JSON/dia_16_json.md new file mode 100644 index 0000000..b2b9b49 --- /dev/null +++ b/Spanish/dia_16_JSON/dia_16_json.md @@ -0,0 +1,602 @@ +
+

30 Días de JavaScript: JSON

+ + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
+ Enero, 2020 +
+ +
+ +[<< Día 15](../dia_15_Clases/dia_15_clases.md) | [Día 17 >>](..) + +![Thirty Days Of JavaScript](../images/banners/day_1_16.png) + +- [Día 16](#día-16) + - [JSON](#json) + - [Convertir JSON en objeto JavaScript](#convertir-json-en-objeto-javascript) + - [JSON.parse()](#jsonparse) + - [Uso de una función de recuperación con JSON.parse()](#uso-de-una-función-de-recuperación-con-jsonparse) + - [Conversión de objetos a JSON](#conversión-de-objetos-a-json) + - [Usando un filtro de array con JSON.stringify](#usando-un-filtro-de-array-con-jsonstringify) + - [Ejercicios](#ejercicios) + - [Ejercicios Nivel 1](#ejercicios-nivel-1) + - [Ejercicios Nivel 2](#ejercicios-nivel-2) + - [Ejercicios Nivel 3](#ejercicios-nivel-3) + +# Día 16 + +## JSON + +JSON son las siglas de JavaScript Object Notation (Notación de objetos de JavaScript). La sintaxis JSON se deriva de la sintaxis de notación de objetos de JavaScript, pero el formato JSON es sólo de texto o cadena. JSON es un formato de datos ligero para almacenar y transportar. JSON se utiliza sobre todo cuando se envían datos de un servidor a un cliente. JSON es una alternativa más fácil de usar que XML. + +**Ejemplo:** + +```js +{ +"users":[ + { + "firstName":"Asabeneh", + "lastName":"Yetayeh", + "age":250, + "email":"asab@asb.com" + }, + { + "firstName":"Alex", + "lastName":"James", + "age":25, + "email":"alex@alex.com" + }, + { + "firstName":"Lidiya", + "lastName":"Tekle", + "age":28, + "email":"lidiya@lidiya.com" + } +] +} +``` + +El ejemplo JSON anterior no es muy diferente de un objeto normal. Entonces, ¿cuál es la diferencia? La diferencia es que la clave de un objeto JSON debe ir con comillas dobles o debe ser una cadena. JavaScript Object y JSON son muy similares por lo que podemos cambiar JSON a Object y Object a JSON. + +Veamos el ejemplo anterior con más detalle, comienza con una llave. Dentro de la corchete, hay una clave "usuarios" que tiene una matriz de valores. Dentro del array tenemos diferentes objetos y cada objeto tiene claves, cada clave tiene que tener comillas dobles. Por ejemplo, utilizamos "firstNaMe" en lugar de sólo firstName, sin embargo en el objeto utilizamos claves sin comillas dobles. Esta es la mayor diferencia entre un objeto y un JSON. Veamos más ejemplos sobre JSON. + +**Ejemplo:** + +```js +{ + "Alex": { + "email": "alex@alex.com", + "skills": [ + "HTML", + "CSS", + "JavaScript" + ], + "age": 20, + "isLoggedIn": false, + "points": 30 + }, + "Asab": { + "email": "asab@asab.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "Redux", + "MongoDB", + "Express", + "React", + "Node" + ], + "age": 25, + "isLoggedIn": false, + "points": 50 + }, + "Brook": { + "email": "daniel@daniel.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React", + "Redux" + ], + "age": 30, + "isLoggedIn": true, + "points": 50 + }, + "Daniel": { + "email": "daniel@alex.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "Python" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + }, + "John": { + "email": "john@john.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React", + "Redux", + "Node.js" + ], + "age": 20, + "isLoggedIn": true, + "points": 50 + }, + "Thomas": { + "email": "thomas@thomas.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + }, + "Paul": { + "email": "paul@paul.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "MongoDB", + "Express", + "React", + "Node" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + } +} +``` + +### Convertir JSON en objeto JavaScript + +La mayoría de las veces obtenemos los datos JSON de la respuesta HTTP o de un archivo, pero podemos almacenar el JSON como una cadena y podemos cambiarlo por un objeto para la demostración. En JavaScript la palabra clave _JSON_ tiene los métodos _parse()_ y _stringify()_. Cuando queremos cambiar el JSON a un objeto, parseamos el JSON usando _JSON.parse()_. Cuando queremos pasar el objeto a JSON utilizamos _JSON.stringify()_. + +#### JSON.parse() + +```js +JSON.parse(json[, reviver]) +// json or text , los datos +//reviver es una función opcional de callback +/* JSON.parse(json, (key, value) => { + +}) +*/ +``` + +```js +const usersText = `{ +"users":[ + { + "firstName":"Asabeneh", + "lastName":"Yetayeh", + "age":250, + "email":"asab@asb.com" + }, + { + "firstName":"Alex", + "lastName":"James", + "age":25, + "email":"alex@alex.com" + }, + { + "firstName":"Lidiya", + "lastName":"Tekle", + "age":28, + "email":"lidiya@lidiya.com" + } +] +}`; + +const usersObj = JSON.parse(usersText, undefined, 4); +console.log(usersObj); +``` + +### Uso de una función de recuperación con JSON.parse() + +Para utilizar la función reviver como formateador, ponemos las claves que queremos para formatear el valor del nombre y del apellido. Digamos que estamos interesados en formatear el nombre y el apellido de los datos JSON. + +```js +const usersText = `{ +"users":[ + { + "firstName":"Asabeneh", + "lastName":"Yetayeh", + "age":250, + "email":"asab@asb.com" + }, + { + "firstName":"Alex", + "lastName":"James", + "age":25, + "email":"alex@alex.com" + }, + { + "firstName":"Lidiya", + "lastName":"Tekle", + "age":28, + "email":"lidiya@lidiya.com" + } +] +}`; + +const usersObj = JSON.parse(usersText, (key, value) => { + let newValue = + typeof value == "string" && key != "email" ? value.toUpperCase() : value; + return newValue; +}); +console.log(usersObj); +``` + +El _JSON.parse()_ es muy práctico de usar. No tienes que pasar el parámetro opcional, puedes simplemente usarlo con el parámetro requerido y lograrás bastante. + +### Conversión de objetos a JSON + +Cuando queremos pasar el objeto a JSON utilizamos _JSON.stringify()_. El método stringify toma un parámetro obligatorio y dos opcionales. _Replacer_ se utiliza como filtro y _space_ es una indentación. Si no queremos filtrar ninguna de las claves del objeto podemos pasar simplemente undefined. + +```js +JSON.stringify(obj, replacer, space); +// json or text , los datos +// reviver es una función opcional de callback +``` + +Convirtamos el siguiente objeto en una cadena. Primero mantengamos todas las claves y también tengamos una indentación de 4 espacios. + +```js +const users = { + Alex: { + email: "alex@alex.com", + skills: ["HTML", "CSS", "JavaScript"], + age: 20, + isLoggedIn: false, + points: 30, + }, + Asab: { + email: "asab@asab.com", + skills: [ + "HTML", + "CSS", + "JavaScript", + "Redux", + "MongoDB", + "Express", + "React", + "Node", + ], + age: 25, + isLoggedIn: false, + points: 50, + }, + Brook: { + email: "daniel@daniel.com", + skills: ["HTML", "CSS", "JavaScript", "React", "Redux"], + age: 30, + isLoggedIn: true, + points: 50, + }, + Daniel: { + email: "daniel@alex.com", + skills: ["HTML", "CSS", "JavaScript", "Python"], + age: 20, + isLoggedIn: false, + points: 40, + }, + John: { + email: "john@john.com", + skills: ["HTML", "CSS", "JavaScript", "React", "Redux", "Node.js"], + age: 20, + isLoggedIn: true, + points: 50, + }, + Thomas: { + email: "thomas@thomas.com", + skills: ["HTML", "CSS", "JavaScript", "React"], + age: 20, + isLoggedIn: false, + points: 40, + }, + Paul: { + email: "paul@paul.com", + skills: [ + "HTML", + "CSS", + "JavaScript", + "MongoDB", + "Express", + "React", + "Node", + ], + age: 20, + isLoggedIn: false, + points: 40, + }, +}; + +const txt = JSON.stringify(users, undefined, 4); +console.log(txt); // text significa JSON- porque json es una forma de cadena de un objeto. +``` + +```sh +{ + "Alex": { + "email": "alex@alex.com", + "skills": [ + "HTML", + "CSS", + "JavaScript" + ], + "age": 20, + "isLoggedIn": false, + "points": 30 + }, + "Asab": { + "email": "asab@asab.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "Redux", + "MongoDB", + "Express", + "React", + "Node" + ], + "age": 25, + "isLoggedIn": false, + "points": 50 + }, + "Brook": { + "email": "daniel@daniel.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React", + "Redux" + ], + "age": 30, + "isLoggedIn": true, + "points": 50 + }, + "Daniel": { + "email": "daniel@alex.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "Python" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + }, + "John": { + "email": "john@john.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React", + "Redux", + "Node.js" + ], + "age": 20, + "isLoggedIn": true, + "points": 50 + }, + "Thomas": { + "email": "thomas@thomas.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + }, + "Paul": { + "email": "paul@paul.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "MongoDB", + "Express", + "React", + "Node" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + } +} +``` + +### Usando un filtro de array con JSON.stringify + +Ahora, vamos a utilizar replacer como un filtro. El objeto usuario tiene una larga lista de claves, pero sólo nos interesan algunas de ellas. Ponemos las claves que queremos conservar en un array como se muestra en el ejemplo y lo utilizamos en lugar del replacer. + +```js +const user = { + firstName: "Asabeneh", + lastName: "Yetayeh", + country: "Finland", + city: "Helsinki", + email: "alex@alex.com", + skills: ["HTML", "CSS", "JavaScript", "React", "Python"], + age: 250, + isLoggedIn: false, + points: 30, +}; + +const txt = JSON.stringify( + user, + ["firstName", "lastName", "country", "city", "age"], + 4 +); +console.log(txt); +``` + +```sh +{ + "firstName": "Asabeneh", + "lastName": "Yetayeh", + "country": "Finland", + "city": "Helsinki", + "age": 250 +} +``` + +🌕 Eres extraordinario. Ahora, ya conoces un formato de datos ligero que puedes utilizar para almacenar datos o para enviarlos a un servidor HTTP. Llevas 16 pasos de ventaja en tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tus músculos. + +## Ejercicios + +```js +const skills = ["HTML", "CSS", "JS", "React", "Node", "Python"]; +let age = 250; +let isMarried = true; +const student = { + firstName: "Asabeneh", + lastName: "Yetayehe", + age: 250, + isMarried: true, + skills: ["HTML", "CSS", "JS", "React", "Node", "Python"], +}; +const txt = `{ + "Alex": { + "email": "alex@alex.com", + "skills": [ + "HTML", + "CSS", + "JavaScript" + ], + "age": 20, + "isLoggedIn": false, + "points": 30 + }, + "Asab": { + "email": "asab@asab.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "Redux", + "MongoDB", + "Express", + "React", + "Node" + ], + "age": 25, + "isLoggedIn": false, + "points": 50 + }, + "Brook": { + "email": "daniel@daniel.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React", + "Redux" + ], + "age": 30, + "isLoggedIn": true, + "points": 50 + }, + "Daniel": { + "email": "daniel@alex.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "Python" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + }, + "John": { + "email": "john@john.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React", + "Redux", + "Node.js" + ], + "age": 20, + "isLoggedIn": true, + "points": 50 + }, + "Thomas": { + "email": "thomas@thomas.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "React" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + }, + "Paul": { + "email": "paul@paul.com", + "skills": [ + "HTML", + "CSS", + "JavaScript", + "MongoDB", + "Express", + "React", + "Node" + ], + "age": 20, + "isLoggedIn": false, + "points": 40 + } +} +`; +``` + +### Ejercicios Nivel 1 + +1. Cambiar el array de habilidades a JSON usando JSON.stringify() +1. Stringify la variable de la edad +1. Stringify la variable isMarried +1. Stringify el objeto estudiante + +### Ejercicios Nivel 2 + +1. Stringify el objeto estudiantes con sólo las propiedades firstName, lastName y skills + +### Ejercicios Nivel 3 + +1. Parsear el _txt_ JSON a objeto. +2. Encuentra el usuario que tiene muchas habilidades de la variable almacenada en _txt_. + +🎉 ¡FELICITACIONES! 🎉 + +[<< Día 15](../dia_15_Clases/dia_15_clases.md) | [Día 17 >>](..) From f6e2e5da00db5056c5d9112f3dc6cfe46eb1ddc3 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Mon, 19 Sep 2022 00:15:43 -0500 Subject: [PATCH 03/26] Spanish translation day 17 of 30 --- Spanish/dia_16_JSON/dia_16_json.md | 4 +- .../dia_17_web_storages.md | 233 ++++++++++++++++++ 2 files changed, 235 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_17_Web_storages/dia_17_web_storages.md diff --git a/Spanish/dia_16_JSON/dia_16_json.md b/Spanish/dia_16_JSON/dia_16_json.md index b2b9b49..c95fd73 100644 --- a/Spanish/dia_16_JSON/dia_16_json.md +++ b/Spanish/dia_16_JSON/dia_16_json.md @@ -14,7 +14,7 @@ -[<< Día 15](../dia_15_Clases/dia_15_clases.md) | [Día 17 >>](..) +[<< Día 15](../dia_15_Clases/dia_15_clases.md) | [Día 17 >>](../dia_17_Web_storages/dia_17_web_storages.md) ![Thirty Days Of JavaScript](../images/banners/day_1_16.png) @@ -599,4 +599,4 @@ const txt = `{ 🎉 ¡FELICITACIONES! 🎉 -[<< Día 15](../dia_15_Clases/dia_15_clases.md) | [Día 17 >>](..) +[<< Día 15](../dia_15_Clases/dia_15_clases.md) | [Día 17 >>](../dia_17_Web_storages/dia_17_web_storages.md) diff --git a/Spanish/dia_17_Web_storages/dia_17_web_storages.md b/Spanish/dia_17_Web_storages/dia_17_web_storages.md new file mode 100644 index 0000000..069a713 --- /dev/null +++ b/Spanish/dia_17_Web_storages/dia_17_web_storages.md @@ -0,0 +1,233 @@ +
+

30 Días de JavaScript: Web Storages

+ + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
+ Enero, 2020 +
+ +
+ +[<< Día 16](../dia_16_JSON/dia_16_json.md) | [Día 18 >>](..) + +![Thirty Days Of JavaScript](../images/banners/day_1_17.png) + +- [Día 17](#día-17) + - [Storage (Almacenamiento) web HTML5](#storage-almacenamiento-web-html5) + - [sessionStorage](#sessionstorage) + - [localStorage](#localstorage) + - [Caso de uso de los almacenamientos web](#caso-de-uso-de-los-almacenamientos-web) + - [Objetos de almacenamiento web HTML5](#objetos-de-almacenamiento-web-html5) + - [Establecer el elemento en el localStorage](#establecer-el-elemento-en-el-localstorage) + - [Obtener un elemento de localStorage](#obtener-un-elemento-de-localstorage) + - [Limpiando el localStorage](#limpiando-el-localstorage) + - [Ejercicios](#ejercicios) + - [Ejercicios: Nivel 1](#ejercicios-nivel-1) + - [Ejercicios: Nivel 2](#ejercicios-nivel-2) + - [Ejercicios: Nivel 3](#ejercicios-nivel-3) + +# Día 17 + +## Storage (Almacenamiento) web HTML5 + +Web Storage (sessionStorage y localStorage) es una nueva API de HTML5 que ofrece importantes ventajas sobre las cookies tradicionales. Antes de HTML5, los datos de las aplicaciones debían almacenarse en cookies, incluidas en cada solicitud del servidor. Web storage es más seguro, y se pueden almacenar grandes cantidades de datos localmente, sin afectar al rendimiento del sitio web. El límite de almacenamiento de datos de las cookies en muchos navegadores web es de unos 4 KB por cookie. Nosotros almacenamos datos mucho más grandes (al menos 5MB) y nunca los transferimos al servidor. Todos los sitios del mismo o único origen pueden almacenar y acceder a los mismos datos. + +Se puede acceder a los datos almacenados mediante JavaScript, lo que permite aprovechar las secuencias de comandos del lado del cliente para hacer muchas cosas que tradicionalmente han implicado la programación del lado del servidor y las bases de datos relacionales. Hay dos objetos de almacenamiento web: + +- sessionStorage +- localStorage + +localStorage es similar a sessionStorage, excepto que mientras los datos almacenados en localStorage no tienen tiempo de caducidad, los datos almacenados en sessionStorage se borran cuando termina la sesión de la página, es decir, cuando se cierra la página. + +Hay que tener en cuenta que los datos almacenados en localStorage o sessionStorage son específicos del protocolo de la página. + +Las claves y los valores son siempre cadenas (tenga en cuenta que, al igual que con los objetos, las claves enteras se convertirán automáticamente en cadenas). + +![web_storage](../images/web_storage.png) + +### sessionStorage + +sessionStorage sólo está disponible dentro de la sesión de la pestaña o ventana del navegador. Está diseñado para almacenar datos en una sola sesión de la página web. Esto significa que si la ventana se cierra, los datos de la sesión se eliminarán. Como sessionStorage y localStorage tienen métodos similares, nos centraremos sólo en localStorage. + +### localStorage + +El localStorage de HTML5 es la para la API de almacenamiento web que se utiliza para almacenar datos en el navegador sin caducidad. Los datos estarán disponibles en el navegador incluso después de cerrarlo. localStorage se mantiene incluso entre sesiones del navegador. Esto significa que los datos siguen estando disponibles cuando se cierra y se vuelve a abrir el navegador, y también de forma instantánea entre pestañas y ventanas. + +En ambos casos, los datos del almacenamiento web no están disponibles entre distintos navegadores. Por ejemplo, no se puede acceder a los objetos de almacenamiento creados en Firefox en Internet Explorer, exactamente igual que las cookies. Hay cinco métodos para trabajar en el almacenamiento local: +_setItem(), getItem(), removeItem(), clear(), key()_ + +### Caso de uso de los almacenamientos web + +Algunos casos de uso de los almacenes web son + +- almacenar datos temporalmente. +- guardar los productos que el usuario pone en su carrito de la compra. +- los datos pueden estar disponibles entre peticiones de página, múltiples pestañas del navegador y también entre sesiones del navegador utilizando localStorage. +- puede utilizarse completamente sin conexión utilizando localStorage. +- El almacenamiento en la web puede suponer una gran ganancia de rendimiento cuando algunos datos estáticos se almacenan en el cliente para minimizar el número de peticiones posteriores. Incluso las imágenes pueden almacenarse en cadenas utilizando la codificación Base64. +- se puede utilizar para el método de autenticación del usuario. + +Para los ejemplos mencionados anteriormente, tiene sentido utilizar localStorage. Te preguntarás, entonces, cuándo debemos utilizar sessionStorage. + +En algunos casos, queremos deshacernos de los datos en cuanto se cierra la ventana. O, quizás, si no queremos que la aplicación interfiera con la misma aplicación que está abierta en otra ventana. Estos escenarios se sirven mejor con sessionStorage. + +Ahora, vamos a ver cómo hacer uso de estas APIs de almacenamiento web. + +## Objetos de almacenamiento web HTML5 + +El almacenamiento (storage) web HTML proporciona dos objetos para almacenar datos en el cliente: + +- window.localStorage - almacena datos sin fecha de caducidad +- window.sessionStorage - almacena datos para una sesión (los datos se pierden cuando se cierra la pestaña del navegador)La mayoría de los navegadores modernos soportan Web Storage, sin embargo es bueno comprobar el soporte del navegador para localStorage y sessionStorage. Veamos los métodos disponibles para los objetos Web Storage. + +Objetos Web Storage: + +- _localStorage_ - para mostrar el objeto localStorage +- _localStorage.clear()_ - para remover todo lo que hay en el almacenamiento local +- _localStorage.setItem()_ - para almacenar datos en el localStorage. Toma como parámetros una clave y un valor. +- _localStorage.getItem()_ - para mostrar los datos almacenados en el localStorage. Toma una clave como parámetro. +- _localStorage.removeItem()_ - para remover un ítem almacenado de un localStorage. Toma la clave como parámetro. +- _localStorage.key()_ - para mostrar un dato almacenado en un localStorage. Toma el índice como parámetro. + +![local_storage](../images/local_storage.png) + +### Establecer el elemento en el localStorage + +Cuando establecemos conjunto los datos que se almacenan en un localStorage, se almacenarán como una cadena. Si estamos almacenando un array o un objeto, debemos encadenarlo primero para mantener el formato, a menos que perdamos la estructura del array o del objeto de los datos originales. + +Almacenamos los datos en el localStorage utilizando el método _localStorage.setItem_. + +```js +//sintaxis +localStorage.setItem("key", "value"); +``` + +- Almacenamiento de una cadena en un localStorage + +```js +localStorage.setItem("firstName", "Asabeneh"); // ya que el valor es una cadena, no lo encadenamos +console.log(localStorage); +``` + +```sh +Storage {firstName: 'Asabeneh', length: 1} +``` + +- Almacenar el número en un storage local + +```js +localStorage.setItem("age", 200); +console.log(localStorage); +``` + +```sh + Storage {age: '200', firstName: 'Asabeneh', length: 2} +``` + +- Almacenando un array en un localStorage. Si estamos almacenando un array, un objeto o una matriz de objetos, debemos encadenar el objeto primero. Véase el ejemplo siguiente. + +```js +const skills = ["HTML", "CSS", "JS", "React"]; +//El array de Skills tiene que ser encadenado primero para mantener el formato. +const skillsJSON = JSON.stringify(skills, undefined, 4); +localStorage.setItem("skills", skillsJSON); +console.log(localStorage); +``` + +```sh +Storage {age: '200', firstName: 'Asabeneh', skills: 'HTML,CSS,JS,React', length: 3} +``` + +```js +let skills = [ + { tech: "HTML", level: 10 }, + { tech: "CSS", level: 9 }, + { tech: "JS", level: 8 }, + { tech: "React", level: 9 }, + { tech: "Redux", level: 10 }, + { tech: "Node", level: 8 }, + { tech: "MongoDB", level: 8 }, +]; + +let skillJSON = JSON.stringify(skills); +localStorage.setItem("skills", skillJSON); +``` + +- Almacenamiento de un objeto en un localStorage. Antes de almacenar los objetos en un localStorage, el objeto tiene que ser stringificado. + +```js +const user = { + firstName: "Asabeneh", + age: 250, + skills: ["HTML", "CSS", "JS", "React"], +}; + +const userText = JSON.stringify(user, undefined, 4); +localStorage.setItem("user", userText); +``` + +### Obtener un elemento de localStorage + +Obtenemos los datos del almacenamiento local utilizando el método _localStorage.getItem()_. + +```js +//sintaxis +localStorage.getItem("key"); +``` + +```js +let firstName = localStorage.getItem("firstName"); +let age = localStorage.getItem("age"); +let skills = localStorage.getItem("skills"); +console.log(firstName, age, skills); +``` + +```sh + 'Asabeneh', '200', '['HTML','CSS','JS','React']' +``` + +Como puedes ver la habilidad está en un formato de cadena. Utilicemos JSON.parse() para convertirlo en un array normal. + +```js +let skills = localStorage.getItem("skills"); +let skillsObj = JSON.parse(skills, undefined, 4); +console.log(skillsObj); +``` + +```sh +['HTML','CSS','JS','React'] +``` + +### Limpiando el localStorage + +El método clear, borrará todo lo almacenado en la memoria local + +```js +localStorage.clear(); +``` + +🌕 Estás decidido. Ahora, conociste un Web Storages y supiste cómo almacenar pequeños datos en los navegadores de los clientes. Llevas 17 pasos de ventaja en tu camino hacia la grandeza. Ahora haz algunos ejercicios para tu cerebro y para tu músculo. + +## Ejercicios + +### Ejercicios: Nivel 1 + +1. Guarda tu nombre, apellido, edad, país y ciudad en tu navegador localStorage. + +### Ejercicios: Nivel 2 + +1. Cree un objeto estudiante. El objeto estudiante tendrá el nombre, el apellido, la edad, las habilidades, el país, las claves inscritas y los valores para las claves. Almacena el objeto estudiante en el localStorage de tu navegador. + +### Ejercicios: Nivel 3 + +1. Crear un objeto llamado personAccount. Tiene propiedades de nombre, apellido, ingresos, gastos y tiene métodos 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 y su descripción. + +🎉 ¡FELICITACIONES! 🎉 + +[<< Día 16](../dia_16_JSON/dia_16_json.md) | [Día 18 >>](..) From 31a0721d0760e046012ffa9ba00ae6c4eb9969ac Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Mon, 26 Sep 2022 01:00:26 -0500 Subject: [PATCH 04/26] Spanish translation day 18 of 30 --- .../dia_17_web_storages.md | 4 +- Spanish/dia_18_Promesas/dia_18_Promesas.md | 273 ++++++++++++++++++ 2 files changed, 275 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_18_Promesas/dia_18_Promesas.md diff --git a/Spanish/dia_17_Web_storages/dia_17_web_storages.md b/Spanish/dia_17_Web_storages/dia_17_web_storages.md index 069a713..64d8694 100644 --- a/Spanish/dia_17_Web_storages/dia_17_web_storages.md +++ b/Spanish/dia_17_Web_storages/dia_17_web_storages.md @@ -14,7 +14,7 @@ -[<< 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) @@ -230,4 +230,4 @@ localStorage.clear(); 🎉 ¡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) diff --git a/Spanish/dia_18_Promesas/dia_18_Promesas.md b/Spanish/dia_18_Promesas/dia_18_Promesas.md new file mode 100644 index 0000000..a9aebc5 --- /dev/null +++ b/Spanish/dia_18_Promesas/dia_18_Promesas.md @@ -0,0 +1,273 @@ +
+

30 Días de JavaScript: Promesas

+ + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
+ Enero, 2020 +
+ +
+ +[<< Día 17](../dia_17_Web_storages/dia_17_web_storages.md) | [Día 19>>](..) + +![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 {: 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>>](..) From 44e4782cb907e156e5d43b16839f20164c2214b8 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Mon, 26 Sep 2022 01:24:16 -0500 Subject: [PATCH 05/26] Spanish translation day 19 of 30 --- Spanish/dia_18_Promesas/dia_18_Promesas.md | 4 +- Spanish/dia_19_Closures/dia_19_closures.md | 105 +++++++++++++++++++++ 2 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_19_Closures/dia_19_closures.md diff --git a/Spanish/dia_18_Promesas/dia_18_Promesas.md b/Spanish/dia_18_Promesas/dia_18_Promesas.md index a9aebc5..8af01c8 100644 --- a/Spanish/dia_18_Promesas/dia_18_Promesas.md +++ b/Spanish/dia_18_Promesas/dia_18_Promesas.md @@ -14,7 +14,7 @@ -[<< Día 17](../dia_17_Web_storages/dia_17_web_storages.md) | [Día 19>>](..) +[<< 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) @@ -270,4 +270,4 @@ const catsAPI = "https://api.thecatapi.com/v1/breeds"; 🎉 ¡FELICITACIONES! 🎉 -[<< Día 17](../dia_17_Web_storages/dia_17_web_storages.md) | [Día 19>>](..) +[<< Día 17](../dia_17_Web_storages/dia_17_web_storages.md) | [Día 19>>](../dia_19_Closures/dia_19_closures.md) diff --git a/Spanish/dia_19_Closures/dia_19_closures.md b/Spanish/dia_19_Closures/dia_19_closures.md new file mode 100644 index 0000000..4f6df25 --- /dev/null +++ b/Spanish/dia_19_Closures/dia_19_closures.md @@ -0,0 +1,105 @@ +
+

30 Días de JavaScript: Closures

+ + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
+ Enero, 2020 +
+ +
+ +[<< Día 18](../dia_18_Promesas/dia_18_Promesas.md) | [Día 20 >>](..) + +![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 >>](..) From debd7b2f6b7da1554153aa641f8c2c8a388118e2 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Mon, 26 Sep 2022 02:34:24 -0500 Subject: [PATCH 06/26] Spanish translation day 20 of 30 --- Spanish/dia_19_Closures/dia_19_closures.md | 4 +- .../dia_20_escribiendo_codigos_limpios.md | 376 ++++++++++++++++++ 2 files changed, 378 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md diff --git a/Spanish/dia_19_Closures/dia_19_closures.md b/Spanish/dia_19_Closures/dia_19_closures.md index 4f6df25..d9be01e 100644 --- a/Spanish/dia_19_Closures/dia_19_closures.md +++ b/Spanish/dia_19_Closures/dia_19_closures.md @@ -14,7 +14,7 @@ -[<< Día 18](../dia_18_Promesas/dia_18_Promesas.md) | [Día 20 >>](..) +[<< 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) @@ -102,4 +102,4 @@ console.log(innerFuncs.minusOne); 🎉 ¡FELICITACIONES! 🎉 -[<< Día 18](../dia_18_Promesas/dia_18_Promesas.md) | [Día 20 >>](..) +[<< Día 18](../dia_18_Promesas/dia_18_Promesas.md) | [Día 20 >>](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md) diff --git a/Spanish/dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md b/Spanish/dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md new file mode 100644 index 0000000..b645d5d --- /dev/null +++ b/Spanish/dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md @@ -0,0 +1,376 @@ +
+

30 Días de JavaScript: Escribiendo Códigos Limpios

+ + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
+ Enero, 2020 +
+ +
+ +[<< Día 19](../dia_19_Closures/dia_19_closures.md) | [Día 21 >>](..) + +![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 >>](..) From 112cb41468f2053698f6e184dea09e46ee3d5c0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yi=C4=9Fit=20Tosun?= Date: Mon, 26 Sep 2022 13:29:49 +0300 Subject: [PATCH 07/26] Translate 15_Day_Classes to Turkish --- Turkish/15_Day_Classes/15_day_classes.md | 715 +++++++++++++++++++++++ 1 file changed, 715 insertions(+) create mode 100644 Turkish/15_Day_Classes/15_day_classes.md diff --git a/Turkish/15_Day_Classes/15_day_classes.md b/Turkish/15_Day_Classes/15_day_classes.md new file mode 100644 index 0000000..73fc4e0 --- /dev/null +++ b/Turkish/15_Day_Classes/15_day_classes.md @@ -0,0 +1,715 @@ +
+

30 Days Of JavaScript: Classes

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ January, 2020 +
+ +
+ +[<< 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) From 852a72f8a036a460bde5bdcde7b20b8fcf3edfc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yi=C4=9Fit=20Tosun?= Date: Mon, 26 Sep 2022 13:32:44 +0300 Subject: [PATCH 08/26] Fix image path in header --- Turkish/15_Day_Classes/15_day_classes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Turkish/15_Day_Classes/15_day_classes.md b/Turkish/15_Day_Classes/15_day_classes.md index 73fc4e0..3d783b4 100644 --- a/Turkish/15_Day_Classes/15_day_classes.md +++ b/Turkish/15_Day_Classes/15_day_classes.md @@ -16,7 +16,7 @@ [<< 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) +![Thirty Days Of JavaScript](../../images/banners/day_1_15.png) - [Gün 15](#gün-15) - [Sınıflar](#sınıflar) From 6e4332d52b1059560e2773d99f13c6c4c51fdac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yi=C4=9Fit=20Tosun?= Date: Thu, 29 Sep 2022 10:09:57 +0300 Subject: [PATCH 09/26] Translate '14_day_error_handling' to Turkish --- .../14_day_error_handling.md | 58 +++++++++---------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/14_Day_Error_handling/14_day_error_handling.md b/14_Day_Error_handling/14_day_error_handling.md index bc17c5d..2ee0980 100644 --- a/14_Day_Error_handling/14_day_error_handling.md +++ b/14_Day_Error_handling/14_day_error_handling.md @@ -14,11 +14,11 @@ -[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md) +[<< 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) +![Thirty Days Of JavaScript](../../images/banners/day_1_14.png) -- [Day 14](#day-14) +- [Gün 14](#day-14) - [Error Handling](#error-handling) - [Error Types](#error-types) - [Exercises](#exercises) @@ -26,31 +26,31 @@ - [Exercises: Level 2](#exercises-level-2) - [Exercises:Level](#exerciseslevel) -# Day 14 +# Gün 14 ## Error Handling -JavaScript is a loosely-typed language. Some times you will get a runtime error when you try to access an undefined variable or call undefined function etc. +JavaScript 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 similar to python or Java provides an error-handling mechanism to catch runtime errors using try-catch-finally block. +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 { - // code that may throw an error + // hata verilebilicek kod } catch (err) { - // code to be executed if an error occurs + // bir hata oluşursa çalıştırılacak kod } finally { - // code to be executed regardless of an error occurs or not + // bir hatanın oluşup oluşmadığına bakılmaksızın yürütülecek kod } ``` -**try**: wrap suspicious code that may throw an error in try block.The try statement allows us to define a block of code to be tested for errors while it is being executed. +**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**: write code to do something in catch block when an error occurs. The catch block can have parameters that will give you error information. Catch block is used to log an error or display specific messages to the user. +**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 block will always be executed regardless of the occurrence of an error. The finally block can be used to complete the remaining task or reset variables that might have changed before error occurred in try block. +**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. -**Example:** +**Örnek:** ```js try { @@ -83,7 +83,7 @@ ReferenceError: fistName is not defined 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. +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 { @@ -103,7 +103,7 @@ Error message fistName is not defined In any case I will be executed ``` -throw: the throw statement allows us to create a custom error. We can through a string, number, boolean or an object. Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception: +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 @@ -131,7 +131,7 @@ throwErrorExampleFun() ### Error Types -- ReferenceError: An illegal reference has occurred. A ReferenceError is thrown if we use a variable that has not been declared. +- ReferenceError: Geçersiz bir referans oluşturur. Tanımlanmamış bir değişken kullanırsak bir ReferenceError atılır. ```js let firstName = 'Asabeneh' @@ -145,7 +145,7 @@ Uncaught ReferenceError: lastName is not defined at :2:35 ``` -- SyntaxError: A syntax error has occurred +- SyntaxError: Bir syntax(sözdizim) hatası oluşturur. ```js let square = 2 x 2 @@ -158,7 +158,7 @@ console.log('Hello, world") Uncaught SyntaxError: Unexpected identifier ``` -- TypeError: A type error has occurred +- TypeError: Bir type hatası oluşturur ```js let num = 10 @@ -170,24 +170,24 @@ Uncaught TypeError: num.toLowerCase is not a function at :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. +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. -🌕 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. +🌕 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. -## Exercises +## Egzersizler -### Exercises:Level 1 +### Egzersiz:Seviye 1 -Practice +Pratik -### Exercises: Level 2 +### Egzersiz: Seviye 2 -Practice +Pratik -### Exercises:Level +### Egzersiz: Seviye 3 -Practice +Pratik -🎉 CONGRATULATIONS ! 🎉 +🎉 TEBRİKLER ! 🎉 -[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md) +[<< Gün 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Gün 15>>](../15_Day_Classes/15_day_classes.md) From 95cfb3cd9d6c3608c257695c21cb931ffc86d209 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yi=C4=9Fit=20Tosun?= Date: Thu, 29 Sep 2022 10:14:10 +0300 Subject: [PATCH 10/26] Delete 14_day_error_handling.md --- .../14_day_error_handling.md | 193 ------------------ 1 file changed, 193 deletions(-) delete mode 100644 14_Day_Error_handling/14_day_error_handling.md diff --git a/14_Day_Error_handling/14_day_error_handling.md b/14_Day_Error_handling/14_day_error_handling.md deleted file mode 100644 index 2ee0980..0000000 --- a/14_Day_Error_handling/14_day_error_handling.md +++ /dev/null @@ -1,193 +0,0 @@ -
-

30 Days Of JavaScript: Error handling

- - - - - Twitter Follow - - -Author: -Asabeneh Yetayeh
- January, 2020 -
- -
- -[<< 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 :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 :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 :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 :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) From 1df4102b871c555e0be30a0fc3e8d2865bdeb25f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yi=C4=9Fit=20Tosun?= Date: Thu, 29 Sep 2022 10:15:34 +0300 Subject: [PATCH 11/26] Translate '14_day_error_handling' to Turkish --- .../14_day_error_handling.md | 193 ++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 Turkish/14_Day_Error_handling/14_day_error_handling.md diff --git a/Turkish/14_Day_Error_handling/14_day_error_handling.md b/Turkish/14_Day_Error_handling/14_day_error_handling.md new file mode 100644 index 0000000..2ee0980 --- /dev/null +++ b/Turkish/14_Day_Error_handling/14_day_error_handling.md @@ -0,0 +1,193 @@ +
+

30 Days Of JavaScript: Error handling

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ January, 2020 +
+ +
+ +[<< 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 :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 :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 :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 :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) From ee365019a5ec053c0bf17d6984741c122b6fdcd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yi=C4=9Fit=20Tosun?= Date: Thu, 29 Sep 2022 10:23:46 +0300 Subject: [PATCH 12/26] Recover deleted 14_day_Error_Handling file --- .../13_day_console_object_methods.md | 164 ++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 14_Day_Error_handling/13_day_console_object_methods.md diff --git a/14_Day_Error_handling/13_day_console_object_methods.md b/14_Day_Error_handling/13_day_console_object_methods.md new file mode 100644 index 0000000..d9fba8d --- /dev/null +++ b/14_Day_Error_handling/13_day_console_object_methods.md @@ -0,0 +1,164 @@ +
+

30 Days Of JavaScript: Error handling

+ + + + + Twitter Follow + + +Author: +Asabeneh Yetayeh
+ January, 2020 +
+ +
+ +[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md) + +![Thirty Days Of JavaScript](../images/banners/day_1_14.png) + +- [Day 14](#day-14) + - [Error Handling](#error-handling) + - [Error Types](#error-types) + - [Exercises](#exercises) + - [Exercises:Level 1](#exerciseslevel-1) + - [Exercises: Level 2](#exercises-level-2) + - [Exercises:Level](#exerciseslevel) + +# Day 14 + +## Error Handling + +JavaScript is a loosely-typed language. Some times you will get a runtime error when you try to access an undefined variable or call undefined function etc. + +JavaScript similar to python or Java provides an error-handling mechanism to catch runtime errors using try-catch-finally block. + +```js +try { + // code that may throw an error +} catch (err) { + // code to be executed if an error occurs +} finally { + // code to be executed regardless of an error occurs or not +} +``` + +**try**: wrap suspicious code that may throw an error in try block.The try statement allows us to define a block of code to be tested for errors while it is being executed. + +**catch**: write code to do something in catch block when an error occurs. The catch block can have parameters that will give you error information. Catch block is used to log an error or display specific messages to the user. + +**finally**: finally block will always be executed regardless of the occurrence of an error. The finally block can be used to complete the remaining task or reset variables that might have changed before error occurred in try block. + +**Example:** + +```js +try { + let lastName = 'Yetayeh' + let fullName = fistName + ' ' + lastName +} catch (err) { + console.log(err) +} +``` + +```sh +ReferenceError: fistName is not defined + at :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 :4:20 +In any case it will be executed +``` +The catch block take a parameter. It is common to pass e, err or error as a parameter to the catch block. This parameter is an object and it has name and message keys. Lets use the name and message. +```js +try { + let lastName = 'Yetayeh' + let fullName = fistName + ' ' + lastName +} catch (err) { + console.log('Name of the error', err.name) + console.log('Error message', err.message) +} finally { + console.log('In any case I will be executed') +} +``` +```sh +Name of the error ReferenceError +Error message fistName is not defined +In any case I will be executed +``` +throw: the throw statement allows us to create a custom error. We can through a string, number, boolean or an object. Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception: +```js +throw 'Error2' // generates an exception with a string value +throw 42 // generates an exception with the value 42 +throw true // generates an exception with the value true +throw new Error('Required') // generates an error object with the message of Required +``` +```js +const throwErrorExampleFun = () => { + let message + let x = prompt('Enter a number: ') + try { + if (x == '') throw 'empty' + if (isNaN(x)) throw 'not a number' + x = Number(x) + if (x < 5) throw 'too low' + if (x > 10) throw 'too high' + } catch (err) { + console.log(err) + } +} +throwErrorExampleFun() +``` +### Error Types +- ReferenceError: An illegal reference has occurred. A ReferenceError is thrown if we use a variable that has not been declared. +```js +let firstName = 'Asabeneh' +let fullName = firstName + ' ' + lastName +console.log(fullName) +``` +```sh +Uncaught ReferenceError: lastName is not defined + at :2:35 +``` +- SyntaxError: A syntax error has occurred +```js +let square = 2 x 2 +console.log(square) +console.log('Hello, world") +``` +```sh +Uncaught SyntaxError: Unexpected identifier +``` +- TypeError: A type error has occurred +```js +let num = 10 +console.log(num.toLowerCase()) +``` +```sh +Uncaught TypeError: num.toLowerCase is not a function + at :2:17 +``` +These are some of the common error you may face when you write a code. Understanding errors can help you to know what mistakes you made and it will help you to debug your code fast. +🌕 You are flawless. Now, you knew how to handle errors and you can write robust application which handle unexpected user inputs. You have just completed day 14 challenges and you are 14 steps a head in to your way to greatness. Now do some exercises for your brain and for your muscle. +## Exercises +### Exercises:Level 1 +Practice +### Exercises: Level 2 +Practice +### Exercises:Level +Practice +🎉 CONGRATULATIONS ! 🎉 +[<< Day 13](../13_Day_Console_object_methods/13_day_console_object_methods.md) | [Day 15>>](../15_Day_Classes/15_day_classes.md) \ No newline at end of file From c2226664bdc9cac0e425286fac7a4c42a2ac3e34 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 18:44:04 -0500 Subject: [PATCH 13/26] Spanish translation day 21 of 30 --- .../dia_20_escribiendo_codigos_limpios.md | 4 +- Spanish/dia_21_DOM/dia_21_dom.md | 407 ++++++++++++++++++ 2 files changed, 409 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_21_DOM/dia_21_dom.md diff --git a/Spanish/dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md b/Spanish/dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md index b645d5d..4257786 100644 --- a/Spanish/dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md +++ b/Spanish/dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md @@ -14,7 +14,7 @@ -[<< Día 19](../dia_19_Closures/dia_19_closures.md) | [Día 21 >>](..) +[<< 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) @@ -373,4 +373,4 @@ Sea cual sea la guía de estilo que sigas, sé coherente. Sigue algunos paradigm 🎉 ¡FELICITACIONES! 🎉 -[<< Día 19](../dia_19_Closures/dia_19_closures.md) | [Día 21 >>](..) +[<< Día 19](../dia_19_Closures/dia_19_closures.md) | [Día 21 >>](../dia_21_DOM/dia_21_dom.md) diff --git a/Spanish/dia_21_DOM/dia_21_dom.md b/Spanish/dia_21_DOM/dia_21_dom.md new file mode 100644 index 0000000..ba4a290 --- /dev/null +++ b/Spanish/dia_21_DOM/dia_21_dom.md @@ -0,0 +1,407 @@ +
+

30 Días de JavaScript: Document Object Model(DOM)

+ + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
+ Enero, 2020 +
+ +
+ +[<< Día 20](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md) | [Día 22 >>](..) + +![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 + + + + Document Object Model - (Modelo de objeto de documento) + + +

First Title

+

Second Title

+

Third Title

+

+ + +``` + +#### 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); //

First Title

+``` + +#### 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 + + + + JavaScript para todos:DOM + + +
+

Asabeneh Yetayeh desafíos en 2020

+

Reto 30DaysOfJavaScript

+
    +
    + + + +``` + +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 + + + + JavaScript for Everyone:DOM + + +
    +

    Asabeneh Yetayeh challenges in 2020

    +

    30DaysOfJavaScript Challenge

    +
      +
    • 30DaysOfPython Challenge Done
    • +
    • 30DaysOfJavaScript Challenge Ongoing
    • +
    • 30DaysOfReact Challenge Coming
    • +
    • 30DaysOfFullStack Challenge Coming
    • +
    • 30DaysOfDataAnalysis Challenge Coming
    • +
    • 30DaysOfReactNative Challenge Coming
    • +
    • 30DaysOfMachineLearning Challenge Coming
    • +
    +
    + + + +``` + +### 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 + + + + + JavaScript para todos: DOM + + +
    +

    Asabeneh Yetayeh retos en 2020

    +

    Reto 30DaysOfJavaScript

    +
      +
    • Reto 30DaysOfPython Realizado
    • +
    • Reto 30DaysOfJavaScript en curso
    • +
    • Reto 30DaysOfReact próximamente
    • +
    • Reto 30DaysOfFullStack próximamente
    • +
    • Reto 30DaysOfDataAnalysis próximamente
    • +
    • Reto 30DaysOfReactNative próximamente
    • +
    • Reto 30DaysOfMachineLearning próximamente
    • +
    +
    + + +``` + +![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 >>](..) From 424fc695df0cb2af8515ffc9436d41551399ff83 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 20:01:17 -0500 Subject: [PATCH 14/26] Spanish translation day 22 of 30 --- Spanish/dia_21_DOM/dia_21_dom.md | 4 +- .../dia_22_manipulacion_del_objeto_dom.md | 224 ++++++++++++++++++ 2 files changed, 226 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md diff --git a/Spanish/dia_21_DOM/dia_21_dom.md b/Spanish/dia_21_DOM/dia_21_dom.md index ba4a290..47440d0 100644 --- a/Spanish/dia_21_DOM/dia_21_dom.md +++ b/Spanish/dia_21_DOM/dia_21_dom.md @@ -14,7 +14,7 @@ -[<< Día 20](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md) | [Día 22 >>](..) +[<< 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) @@ -404,4 +404,4 @@ Como has notado, las propiedades de css cuando lo usamos en JavaScript va a ser 🎉 ¡FELICITACIONES! 🎉 -[<< Día 20](../dia_20_Escribiendo_Codigos_Limpios/dia_20_escribiendo_codigos_limpios.md) | [Día 22 >>](..) +[<< 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) diff --git a/Spanish/dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md b/Spanish/dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md new file mode 100644 index 0000000..dc4845e --- /dev/null +++ b/Spanish/dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md @@ -0,0 +1,224 @@ +
    +

    30 Días de JavaScript: Manipulación del Objeto DOM

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + +[<< Día 21](../dia_21_DOM/dia_21_dom.md) | [Día 23 >>](..) + +![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 + + + + Document Object Model:30 Days Of JavaScript + + + + + + +``` + +### 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 + + + + Document Object Model:30 Days Of JavaScript + + + + + + +``` + +### 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 + + + + Document Object Model:30 Days Of JavaScript + + + + + + +``` + +### 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 + + + + + Document Object Model:30 Days Of JavaScript + + + +

    Removing child Node

    +

    Asabeneh Yetayeh challenges in 2020

    +
      +
    • 30DaysOfPython Challenge Done
    • +
    • 30DaysOfJavaScript Challenge Done
    • +
    • 30DaysOfReact Challenge Coming
    • +
    • 30DaysOfFullStack Challenge Coming
    • +
    • 30DaysOfDataAnalysis Challenge Coming
    • +
    • 30DaysOfReactNative Challenge Coming
    • +
    • 30DaysOfMachineLearning Challenge Coming
    • +
    + + + + + +``` + +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 + + + + + Document Object Model:30 Days Of JavaScript + + + +

    Removing child Node

    +

    Asabeneh Yetayeh challenges in 2020

    +
      +
    • 30DaysOfPython Challenge Done
    • +
    • 30DaysOfJavaScript Challenge Done
    • +
    • 30DaysOfReact Challenge Coming
    • +
    • 30DaysOfFullStack Challenge Coming
    • +
    • 30DaysOfDataAnalysis Challenge Coming
    • +
    • 30DaysOfReactNative Challenge Coming
    • +
    • 30DaysOfMachineLearning Challenge Coming
    • +
    + + + + + +``` + +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 >>](..) From 31af27e90b9b77acc2ad87e2f27d84d14bd776df Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 20:51:08 -0500 Subject: [PATCH 15/26] Spanish translation day 23 of 30 --- .../dia_22_manipulacion_del_objeto_dom.md | 4 +- .../dia_23_event_listeners.md | 334 ++++++++++++++++++ 2 files changed, 336 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md diff --git a/Spanish/dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md b/Spanish/dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md index dc4845e..2269680 100644 --- a/Spanish/dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md +++ b/Spanish/dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md @@ -14,7 +14,7 @@ -[<< Día 21](../dia_21_DOM/dia_21_dom.md) | [Día 23 >>](..) +[<< 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) @@ -221,4 +221,4 @@ Compruebe los requisitos de este proyecto a partir de ambas imágenes (jpg y gif 🎉 ¡FELICITACIONES! 🎉 -[<< Día 21](../dia_21_DOM/dia_21_dom.md) | [Día 23 >>](..) +[<< Día 21](../dia_21_DOM/dia_21_dom.md) | [Día 23 >>](../dia_23_Event_Listeners/dia_23_event_listeners.md) diff --git a/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md b/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md new file mode 100644 index 0000000..77bd2c9 --- /dev/null +++ b/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md @@ -0,0 +1,334 @@ +
    +

    30 Días de JavaScript: Event Listeners

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + +[<< Día 22](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md) | [Día 24 >>](..) + +![Thirty Days Of JavaScript](../images/banners/day_1_23.png) + +- [Día 22](#día-22) + - [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 22 + +## 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 + + + + Document Object Model + + + + + + + + +``` + +También se puede adjuntar un evento directamente al elemento HTML como script en línea. + +**Ejemplo: onclick** + +```html + + + + Document Object Model + + + + + + + +``` + +#### 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 + + + + Document Object Model + + + + + + + +``` + +#### 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 + + + + Document Object Model + + + + + + + +``` + +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 + + + + Document Object Model:30 Days Of JavaScript + + + +

    Body Mass Index Calculator

    + + + + + + + + +``` + +#### 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 + + + + Document Object Model:30 Days Of JavaScript + + + +

    Data Binding using input or change event

    + + +

    + + + + +``` + +#### evento de desenfoque + +A diferencia de _input_ o _change_, el evento _blur_ se produce cuando el campo de entrada no está enfocado. + +```js + + + + + Document Object Model:30 Days Of JavaScript + + + +

    Giving feedback using blur event

    + + +

    + + + + + +``` + +#### 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 + + + + Document Object Model:30 Days Of JavaScript + + + +

    Key events: Press any key

    + + + + +``` + +--- + +🌕 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 >>](..) From 3e2251100c2bc52b68c4b2a3bb267797079f4687 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 21:03:22 -0500 Subject: [PATCH 16/26] Spanish translation day 24 of 30 --- .../dia_23_event_listeners.md | 4 +- .../dia_24_proyecto_sistema_solar.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md diff --git a/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md b/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md index 77bd2c9..8a513b3 100644 --- a/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md +++ b/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md @@ -14,7 +14,7 @@ -[<< Día 22](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md) | [Día 24 >>](..) +[<< 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) @@ -331,4 +331,4 @@ Podemos acceder a todos los números de teclas del teclado utilizando diferentes 🎉 ¡FELICITACIONES! 🎉 -[<< Día 22](../dia_22_Manipulacion_del_Objeto_DOM/dia_22_manipulacion_del_objeto_dom.md) | [Día 24 >>](..) +[<< 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) diff --git a/Spanish/dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md b/Spanish/dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md new file mode 100644 index 0000000..ff6d627 --- /dev/null +++ b/Spanish/dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md @@ -0,0 +1,37 @@ +
    +

    30 Días de JavaScript: Mini Proyecto Sistema Solar

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + +[<< Día 23](../dia_23_Event_Listeners/dia_23_event_listeners.md) | [Día 25 >>](..) + +![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 >>](..) From 40cf1f1518b3aaa32eda110c8faed02d37ca0acf Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 21:12:58 -0500 Subject: [PATCH 17/26] Spanish translation day 25 of 30 --- .../dia_24_proyecto_sistema_solar.md | 4 +- ...cion_de_datos_de_los_paises_del_mundo_1.md | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md diff --git a/Spanish/dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md b/Spanish/dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md index ff6d627..8c789aa 100644 --- a/Spanish/dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md +++ b/Spanish/dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md @@ -14,7 +14,7 @@ -[<< Día 23](../dia_23_Event_Listeners/dia_23_event_listeners.md) | [Día 25 >>](..) +[<< 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) @@ -34,4 +34,4 @@ 🎉 ¡FELICITACIONES! 🎉 -[<< Día 23](../dia_23_Event_Listeners/dia_23_event_listeners.md) | [Día 25 >>](..) +[<< 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) diff --git a/Spanish/dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md b/Spanish/dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md new file mode 100644 index 0000000..1759a30 --- /dev/null +++ b/Spanish/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 @@ +
    +

    30 Días de JavaScript: Visualización de Datos de los Países del Mundo

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + +[<< Día 24](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md) | [Día 26 >>](..) + +![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 >>](..) From 51d96f2047d5dfa54fc8830c36fbc4eaf28a857a Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 21:20:21 -0500 Subject: [PATCH 18/26] Spanish translation day 26 of 30 --- ...cion_de_datos_de_los_paises_del_mundo_1.md | 4 +- ...cion_de_datos_de_los_paises_del_mundo_2.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md diff --git a/Spanish/dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md b/Spanish/dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md index 1759a30..0a04ce6 100644 --- a/Spanish/dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md +++ b/Spanish/dia_25_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_1/dia_25_visualizacion_de_datos_de_los_paises_del_mundo_1.md @@ -14,7 +14,7 @@ -[<< Día 24](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md) | [Día 26 >>](..) +[<< 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) @@ -36,4 +36,4 @@ 🎉 ¡FELICITACIONES! 🎉 -[<< Día 24](../dia_24_Proyecto_Sistema_Solar/dia_24_proyecto_sistema_solar.md) | [Día 26 >>](..) +[<< 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) diff --git a/Spanish/dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md b/Spanish/dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md new file mode 100644 index 0000000..d09dc9b --- /dev/null +++ b/Spanish/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 @@ +
    +

    30 Días de JavaScript: Visualización de Datos de los Países del Mundo 2

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + +[<< 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 >>](..) + +![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 >>](..) From bfc07fbcf1a4bb71a55f3bb0551f393acb78c9f8 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 21:31:23 -0500 Subject: [PATCH 19/26] Spanish translation day 27 of 30 --- ...cion_de_datos_de_los_paises_del_mundo_2.md | 4 +- .../27_Day_Mini_project_portfolio.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md diff --git a/Spanish/dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md b/Spanish/dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md index d09dc9b..5e91567 100644 --- a/Spanish/dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md +++ b/Spanish/dia_26_Visualizacion_De_Datos_De_Los_Paises_Del_Mundo_2/dia_26_visualizacion_de_datos_de_los_paises_del_mundo_2.md @@ -14,7 +14,7 @@ -[<< 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 >>](..) +[<< 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) @@ -34,4 +34,4 @@ 🎉 ¡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 >>](..) +[<< 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) diff --git a/Spanish/dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md b/Spanish/dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md new file mode 100644 index 0000000..a47ce70 --- /dev/null +++ b/Spanish/dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md @@ -0,0 +1,37 @@ +
    +

    30 Días de JavaScript: Portafolio

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + +[<< 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 >>](..) + +![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 >>](..) From f69c0f537f6c157783a818bcd13f79c06e614459 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 21:39:42 -0500 Subject: [PATCH 20/26] Spanish translation day 28 of 30 --- .../27_Day_Mini_project_portfolio.md | 4 +- ...ia_28_mini_proyecto_tabla_de_posiciones.md | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md diff --git a/Spanish/dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md b/Spanish/dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md index a47ce70..f7a7532 100644 --- a/Spanish/dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md +++ b/Spanish/dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md @@ -14,7 +14,7 @@ -[<< 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 >>](..) +[<< 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) @@ -34,4 +34,4 @@ 🎉 ¡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 >>](..) +[<< 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) diff --git a/Spanish/dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md b/Spanish/dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md new file mode 100644 index 0000000..c3b95e9 --- /dev/null +++ b/Spanish/dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md @@ -0,0 +1,37 @@ +
    +

    30 Days Of JavaScript: Tabla de Posiciones

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + +[<< Día 27](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md) | [Día 29>>](..) + +![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>>](..) From 19ddac469d354e1d31d799256200da6a77620269 Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 22:14:40 -0500 Subject: [PATCH 21/26] Spanish translation day 29 of 30 --- ...ia_28_mini_proyecto_tabla_de_posiciones.md | 6 +-- ...9_mini_proyecto_animacion_de_caracteres.md | 37 +++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 Spanish/dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md diff --git a/Spanish/dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md b/Spanish/dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md index c3b95e9..95baa8f 100644 --- a/Spanish/dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md +++ b/Spanish/dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md @@ -1,5 +1,5 @@
    -

    30 Days Of JavaScript: Tabla de Posiciones

    +

    30 Días de JavaScript: Tabla de Posiciones

    @@ -14,7 +14,7 @@
    -[<< Día 27](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md) | [Día 29>>](..) +[<< 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) @@ -34,4 +34,4 @@ 🎉 ¡FELICITACIONES! 🎉 -[<< Día 27](../dia_27_Mini_Proyecto_Portafolio/27_Day_Mini_project_portfolio.md) | [Día 29>>](..) +[<< 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) diff --git a/Spanish/dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md b/Spanish/dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md new file mode 100644 index 0000000..73ce9db --- /dev/null +++ b/Spanish/dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md @@ -0,0 +1,37 @@ +
    +

    30 Días de JavaScript: Animación de Caracteres

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + +[<< Día 28](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md) | [Día 30>>](..) + +![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>>](..) From 0f47b7c8f26578851c74c9e8672c3033ee3361ef Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 22:35:30 -0500 Subject: [PATCH 22/26] Spanish translation day 30 of 30 --- ...9_mini_proyecto_animacion_de_caracteres.md | 4 +- .../dia_30_mini_proyecto_final.md | 67 +++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 Spanish/dia_30_Mini_Proyecto_Final/dia_30_mini_proyecto_final.md diff --git a/Spanish/dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md b/Spanish/dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md index 73ce9db..1c18d77 100644 --- a/Spanish/dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md +++ b/Spanish/dia_29_Mini_Proyecto_Animacion_De_Caracteres/dia_29_mini_proyecto_animacion_de_caracteres.md @@ -14,7 +14,7 @@ -[<< Día 28](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md) | [Día 30>>](..) +[<< 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) @@ -34,4 +34,4 @@ 🎉 ¡FELICITACIONES! 🎉 -[<< Día 28](../dia_28_Mini_Proyecto_Tabla_De_Posiciones/dia_28_mini_proyecto_tabla_de_posiciones.md) | [Día 30>>](..) +[<< 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) diff --git a/Spanish/dia_30_Mini_Proyecto_Final/dia_30_mini_proyecto_final.md b/Spanish/dia_30_Mini_Proyecto_Final/dia_30_mini_proyecto_final.md new file mode 100644 index 0000000..aa2fa32 --- /dev/null +++ b/Spanish/dia_30_Mini_Proyecto_Final/dia_30_mini_proyecto_final.md @@ -0,0 +1,67 @@ +
    +

    30 Días de JavaScript: Proyecto Final

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Enero, 2020 +
    + +
    + + +
    + +
    + +
    +Apoya al autor para que cree más material educativo
    +Paypal Logo +
    + +[<< 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) From de038c3736c530dc5ff26bec0757f5eec8e0e30d Mon Sep 17 00:00:00 2001 From: EmmanuelArenas Date: Sun, 2 Oct 2022 22:54:53 -0500 Subject: [PATCH 23/26] Correction of days --- .../dia_03_Boleanos_Operadores_Date.md | 6 +++--- Spanish/dia_05_Arreglos/dia_05_arreglos.md | 2 +- Spanish/dia_07_Funciones/dia_07_funciones.md | 4 ++-- .../dia_09_funciones_de_orden_superior.md | 2 +- Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Spanish/dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md b/Spanish/dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md index 6fb7a6f..dc3e405 100644 --- a/Spanish/dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md +++ b/Spanish/dia_03_Booleanos_Operadores_Date/dia_03_Boleanos_Operadores_Date.md @@ -14,7 +14,7 @@ -[<< 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) @@ -126,7 +126,7 @@ Los operadores aritméticos son operadores matemáticos. - Suma(+): a + b - Resta(-): a - b -- Multiplicación(_): a _ b +- Multiplicación(\*): a \* b - División(/): a / b - Módulo(%): 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. 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) diff --git a/Spanish/dia_05_Arreglos/dia_05_arreglos.md b/Spanish/dia_05_Arreglos/dia_05_arreglos.md index 534effc..7d72fda 100644 --- a/Spanish/dia_05_Arreglos/dia_05_arreglos.md +++ b/Spanish/dia_05_Arreglos/dia_05_arreglos.md @@ -778,4 +778,4 @@ const webTechs = [ 🎉 ¡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) diff --git a/Spanish/dia_07_Funciones/dia_07_funciones.md b/Spanish/dia_07_Funciones/dia_07_funciones.md index aaf820f..b3ffa4a 100644 --- a/Spanish/dia_07_Funciones/dia_07_funciones.md +++ b/Spanish/dia_07_Funciones/dia_07_funciones.md @@ -14,7 +14,7 @@ -[<< 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) @@ -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 🎉 ¡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) diff --git a/Spanish/dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md b/Spanish/dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md index b5b2b38..a0111c5 100644 --- a/Spanish/dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md +++ b/Spanish/dia_09_Funciones_De_Orden_Superior/dia_09_funciones_de_orden_superior.md @@ -704,4 +704,4 @@ const products = [ 🎉 ¡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) diff --git a/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md b/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md index 8a513b3..95cfe6a 100644 --- a/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md +++ b/Spanish/dia_23_Event_Listeners/dia_23_event_listeners.md @@ -18,7 +18,7 @@ ![Thirty Days Of JavaScript](../images/banners/day_1_23.png) -- [Día 22](#día-22) +- [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) @@ -32,7 +32,7 @@ - [Ejercicios](#ejercicios) - [Ejercicios: Nivel 1](#ejercicios-nivel-1) -# Día 22 +# Día 23 ## DOM(Document Object Model)-Día 3 From 01f3b508c87e7f86025876f11e274edde60984df Mon Sep 17 00:00:00 2001 From: "diken.dev" Date: Mon, 24 Oct 2022 23:21:32 -0300 Subject: [PATCH 24/26] portuguese translation --- Portuguese/readMe.md | 679 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 679 insertions(+) create mode 100644 Portuguese/readMe.md diff --git a/Portuguese/readMe.md b/Portuguese/readMe.md new file mode 100644 index 0000000..bfe040f --- /dev/null +++ b/Portuguese/readMe.md @@ -0,0 +1,679 @@ +# 30 Dias de JavaScript + +| # Dia | Tópicos | +| ----- | :-------------------------------------------------------------------------------------------------------------------------------------------------: | +| 01 | [Introdução](./readMe.md) | +| 02 | [Tipos de Dados](./02_Day_Data_types/02_day_data_types.md) | +| 03 | [Booleanos, Operadores, Data](./03_Day_Booleans_operators_date/03_booleans_operators_date.md) | +| 04 | [Condicionais](./04_Day_Conditionals/04_day_conditionals.md) | +| 05 | [Arrays](./05_Day_Arrays/05_day_arrays.md) | +| 06 | [Loops](./06_Day_Loops/06_day_loops.md) | +| 07 | [Funções](./07_Day_Functions/07_day_functions.md) | +| 08 | [Objetos](./08_Day_Objects/08_day_objects.md) | +| 09 | [Higher Order Functions](./09_Day_Higher_order_functions/09_day_higher_order_functions.md) | +| 10 | [Sets and Maps](./10_Day_Sets_and_Maps/10_day_Sets_and_Maps.md) | +| 11 | [Destructuring and Spreading](./11_Day_Destructuring_and_spreading/11_day_destructuring_and_spreading.md) | +| 12 | [Expressões Regulares](./12_Day_Regular_expressions/12_day_regular_expressions.md) | +| 13 | [Método Console Objeto](./13_Day_Console_object_methods/13_day_console_object_methods.md) | +| 14 | [Tratamento de Erros](./14_Day_Error_handling/14_day_error_handling.md) | +| 15 | [Classes](./15_Day_Classes/15_day_classes.md) | +| 16 | [JSON](./16_Day_JSON/16_day_json.md) | +| 17 | [Armazenamento na Web](./17_Day_Web_storages/17_day_web_storages.md) | +| 18 | [Promises](./18_Day_Promises/18_day_promises.md) | +| 19 | [Closure](./19_Day_Closures/19_day_closures.md) | +| 20 | [Escrevendo Código Limpo](./20_Day_Writing_clean_codes/20_day_writing_clean_codes.md) | +| 21 | [DOM](./21_Day_DOM/21_day_dom.md) | +| 22 | [Manipulando DOM Objetos](./22_Day_Manipulating_DOM_object/22_day_manipulating_DOM_object.md) | +| 23 | [Event Listeners](./23_Day_Event_listeners/23_day_event_listeners.md) | +| 24 | [Mini Projeto: Sistema Solar](./24_Day_Project_solar_system/24_day_project_solar_system.md) | +| 25 | [Mini Projeto: Visualização de Dados de Paises do mundo](./25_Day_World_countries_data_visualization_1/25_day_world_countries_data_visualization_1.md) | +| 26 | [Mini Projeto: Visualização de Dados de Paises do mundo 2](./26_Day_World_countries_data_visualization_2/26_day_world_countries_data_visualization_2.md) | +| 27 | [Mini Projeto: Portfólio](./27_Day_Mini_project_portfolio/27_day_mini_project_portfolio.md) | +| 28 | [Mini Projeto: Leaderboard](./28_Day_Mini_project_leaderboard/28_day_mini_project_leaderboard.md) | +| 29 | [Mini Projeto: Caracteres Animados](./29_Day_Mini_project_animating_characters/29_day_mini_project_animating_characters.md) | +| 30 | [Projetos Finais](./30_Day_Mini_project_final/30_day_mini_project_final.md) | + +🧡🧡🧡 HAPPY CODING 🧡🧡🧡 + +
    +Dê suporte ao Autor para criar mais materiais educacionais
    +Paypal Logo +
    + +
    +

    30 Dias de JavaScript: Introdução

    + + + + + Twitter Follow + + +Autor: +Asabeneh Yetayeh
    + Janeiro, 2020 +
    + +
    + +🇬🇧 [English](./readMe.md) +🇪🇸 [Spanish](./Spanish/readme.md) +🇮🇹 [Italian](./Italian/readMe.md) +🇷🇺 [Russian](./RU/README.md) +🇹🇷 [Turkish](./Turkish/readMe.md) +🇦🇿 [Azerbaijan](./Azerbaijani/readMe.md) +🇰🇷 [Korean](./Korea/README.md) +🇻🇳 [Vietnamese](./Vietnamese/README.md) +🇵🇱 [Polish](./Polish/readMe.md) + + +
    + +
    + + +[Dia 2 >>](./02_Day_Data_types/02_day_data_types.md) + +![Trinta Dias de JavaScript](./images/day_1_1.png) + +- [30 dias de JavaScript](#30-days-of-javascript) +- [📔 Dia 1](#-day-1) + - [Introdução](#introduction) + - [Requisitos](#requirements) + - [Setup](#setup) + - [Instalação Node.js](#install-nodejs) + - [Navegador](#browser) + - [Instalando Google Chrome](#installing-google-chrome) + - [Abrindo Google Chrome Console](#opening-google-chrome-console) + - [Escrevendo Código no Browser Console](#writing-code-on-browser-console) + - [Console.log](#consolelog) + - [Console.log com Múltiplos Argumentos](#consolelog-with-multiple-arguments) + - [Comentários](#comments) + - [Sintaxe](#syntax) + - [Aritimética](#arithmetics) + - [Editor de Código](#code-editor) + - [Instalando Visual Studio Code](#installing-visual-studio-code) + - [Como usar o Visual Studio Code](#how-to-use-visual-studio-code) + - [Adicionando JavaScript na Web Page](#adding-javascript-to-a-web-page) + - [Script em Linha](#inline-script) + - [Script Interno](#internal-script) + - [Script Externo](#external-script) + - [Multiplo Scripts Externos](#multiple-external-scripts) + - [Introdução Tipo de Dados](#introduction-to-data-types) + - [Números](#numbers) + - [Strings](#strings) + - [Booleanos](#booleans) + - [Undefined](#undefined) + - [Null](#null) + - [Verificando Tipo de Dados](#checking-data-types) + - [Novamente Comentarios](#comments-again) + - [Variáveis](#variables) +- [💻 Dia 1: Exercícios](#-day-1-exercises) + +# 📔 Dia 1 + +## Introdução + +**Parabéns** Em decidir participar dos 30 dias de JavaScript desafio. Neste desafio você aprenderá tudo que precisa para ser um JavaScript programador, e em general, todo o conceito de programaçao. No fim do desafio voce estará adquirindo o Certificado de conclusão dos 30DiasdeJavaScript desafio. Em caso de precisar de ajuda ou se preferir ajudar outros você pode entrar no [Grupo Telegram](https://t.me/ThirtyDaysOfJavaScript). + +**30DiasDeJavaScript** desafio é um guia tanto para iniciantes e Avançados JavaScript Desenvolvedores, Bem vindo ao JavaScript. JavaScript é a linguagem da internet. Eu me divirto em usar e ensinar JavaScript e eu acredito que voce fará tambem. + +Neste passo a passo do JavaScript Desafio, você aprenderá JavaScript, a mais popular linguagem de programação da história da humanindade. +JavaScript é usado **_para adicionar interatividade aos websites, desenvolvimento de mobile apps, desktop aplicações, jogos_** e nos dias de hoje JavaScript pode ser usado para **_machine learning_** e **_AI_**. +**_JavaScript (JS)_** Teve um aumento na popularidade nos últimos anos e segue como a linguagem de programação líder por seis anos consecutivos e é a linguagem de programação mais usada no GitHub + +## Requisitos + +Sem conhecimentos prévios de programação é exigido para seguir este desafio. Precisará apenas: +1. Motivação +2. Um computador +3. Internet +4. Um navegador +5. Um editor de Código + +## Setup + +Eu acredito que voce tem a motivação e o forte desejo de ser um desenvolvedor, um computador e internet. Se voce tem isso, então você tem tudo para iniciar. + +## Instalando Node.js + +Você pode não precisar do Node.js agora mas você precisará mais tarde. Instalação do [node.js](https://nodejs.org/en/). + +![Node download](images/download_node.png) + +Depois do download click duplo e intalar + +![Instalação node](images/install_node.png) + +Nós podemos verificar se o Node está instalador na nossa máquina local abrindo nosso terminal do dispositivo ou prompt de comando. + +```sh +asabeneh $ node -v +v12.14.0 +``` + +Enquanto fazia este tutorial eu estava usando a versão 12.14.0 do Node, mas agora a recomendada versão do Node.js para dowload é v14.17.6, pelo tempo que você usar este material pode haver versão mais atual do Node.js. + +### Navegador + +Existe muitos navegadores por ai, Entento, Eu fortemente recomento o Google Chrome. + +#### Instalando Google Chrome + +Instalar o [Google Chrome](https://www.google.com.br/chrome/) se você não tem um ainda. Nós podemos escrever um pequeno código de JavaScript no console do browser, mas nós não usamos o console do navegador para desenvolver aplicações. + +![Google Chrome](images/google_chrome.png) + +#### Abrindo o Google Chrome Console + +Você pode abrir o Google Chrome console por um ou outro clicando nos 3 pontos no topo do lado direito do navegador, selecionando _Mais ferramentas -> Ferramenta para desenvolvedores ou usando o atalho do teclado. Eu prefiro os atalhos. + +![Abrindo o chrome](images/opening_developer_tool.png) + +Para abrir o console do Chrome usando o atalho do teclado. + +```sh +Mac +Command+Option+J + +Windows/Linux: +Ctl+Shift+J +``` + +Windows/Linux: +Ctl+Shift+J +``` + +![Opening console](images/opening_chrome_console_shortcut.png) + +After you open the Google Chrome console, try to explore the marked buttons. We will spend most of the time on the Console. The Console is the place where your JavaScript code goes. The Google Console V8 engine changes your JavaScript code to machine code. +Let us write a JavaScript code on the Google Chrome console: + +![write code on console](./images/js_code_on_chrome_console.png) + +#### Writing Code on Browser Console + +We can write any JavaScript code on the Google console or any browser console. However, for this challenge, we only focus on Google Chrome console. Open the console using: + +```sh +Mac +Command+Option+I + +Windows: +Ctl+Shift+I +``` + +##### Console.log + +To write our first JavaScript code, we used a built-in function **console.log()**. We passed an argument as input data, and the function displays the output. We passed `'Hello, World'` as input data or argument in the console.log() function. + +```js +console.log('Hello, World!') +``` + +##### Console.log with Multiple Arguments + +The **`console.log()`** function can take multiple parameters separated by commas. The syntax looks like as follows:**`console.log(param1, param2, param3)`** + +![console log multiple arguments](./images/console_log_multipl_arguments.png) + +```js +console.log('Hello', 'World', '!') +console.log('HAPPY', 'NEW', 'YEAR', 2020) +console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript') +``` + +As you can see from the snippet code above, _`console.log()`_ can take multiple arguments. + +Congratulations! You wrote your first JavaScript code using _`console.log()`_. + +##### Comments + +We can add comments to our code. Comments are very important to make code more readable and to leave remarks in our code. JavaScript does not execute the comment part of our code. In JavaScript, any text line starting with // in JavaScript is a comment, and anything enclosed like this `//` is also a comment. + +**Example: Single Line Comment** + +```js +// This is the first comment +// This is the second comment +// I am a single line comment +``` + +**Example: Multiline Comment** + +```js +/* +This is a multiline comment + Multiline comments can take multiple lines + JavaScript is the language of the web + */ +``` + +##### Syntax + +Programming languages are similar to human languages. English or many other language uses words, phrases, sentences, compound sentences and other more to convey a meaningful message. The English meaning of syntax is _the arrangement of words and phrases to create well-formed sentences in a language_. The technical definition of syntax is the structure of statements in a computer language. Programming languages have syntax. JavaScript is a programming language and like other programming languages it has its own syntax. If we do not write a syntax that JavaScript understands, it will raise different types of errors. We will explore different kinds of JavaScript errors later. For now, let us see syntax errors. + +![Error](images/raising_syntax_error.png) + +I made a deliberate mistake. As a result, the console raises syntax errors. Actually, the syntax is very informative. It informs what type of mistake was made. By reading the error feedback guideline, we can correct the syntax and fix the problem. The process of identifying and removing errors from a program is called debugging. Let us fix the errors: + +```js +console.log('Hello, World!') +console.log('Hello, World!') +``` + +So far, we saw how to display text using the _`console.log()`_. If we are printing text or string using _`console.log()`_, the text has to be inside the single quotes, double quotes, or a backtick. +**Example:** + +```js +console.log('Hello, World!') +console.log("Hello, World!") +console.log(`Hello, World!`) +``` + +#### Arithmetics + +Now, let us practice more writing JavaScript codes using _`console.log()`_ on Google Chrome console for number data types. +In addition to the text, we can also do mathematical calculations using JavaScript. Let us do the following simple calculations. +It is possible to write JavaScript code on Google Chrome console can directly without the **_`console.log()`_** function. However, it is included in this introduction because most of this challenge would be taking place in a text editor where the usage of the function would be mandatory. You can play around directly with instructions on the console. + +![Arithmetic](images/arithmetic.png) + +```js +console.log(2 + 3) // Addition +console.log(3 - 2) // Subtraction +console.log(2 * 3) // Multiplication +console.log(3 / 2) // Division +console.log(3 % 2) // Modulus - finding remainder +console.log(3 ** 2) // Exponentiation 3 ** 2 == 3 * 3 +``` + +### Code Editor + +We can write our codes on the browser console, but it won't be for bigger projects. In a real working environment, developers use different code editors to write their codes. In this 30 dias de JavaScript challenge, we will be using Visual Studio Code. + +#### Installing Visual Studio Code + +Visual Studio Code is a very popular open-source text editor. I would recommend to [download Visual Studio Code](https://code.visualstudio.com/), but if you are in favor of other editors, feel free to follow with what you have. + +![Vscode](images/vscode.png) + +If you installed Visual Studio Code, let us start using it. + +#### How to Use Visual Studio Code + +Open the Visual Studio Code by double-clicking its icon. When you open it, you will get this kind of interface. Try to interact with the labeled icons. + +![Vscode ui](./images/vscode_ui.png) + +![Vscode add project](./images/adding_project_to_vscode.png) + +![Vscode open project](./images/opening_project_on_vscode.png) + +![script file](images/scripts_on_vscode.png) + +![Installing Live Server](images/vsc_live_server.png) + +![running script](./images/running_script.png) + +![coding running](./images/launched_on_new_tab.png) + +## Adding JavaScript to a Web Page + +JavaScript can be added to a web page in three different ways: + +- **_Inline script_** +- **_Internal script_** +- **_External script_** +- **_Multiple External scripts_** + +The following sections show different ways of adding JavaScript code to your web page. + +### Inline Script + +Create a project folder on your desktop or in any location, name it 30DaysOfJS and create an **_`index.html`_** file in the project folder. Then paste the following code and open it in a browser, for example [Chrome](https://www.google.com/chrome/). + +```html + + + + 30DaysOfScript:Inline Script + + + + + +``` + +Now, you just wrote your first inline script. We can create a pop up alert message using the _`alert()`_ built-in function. + +### Internal Script + +The internal script can be written in the _`head`_ or the _`body`_, but it is preferred to put it on the body of the HTML document. +First, let us write on the head part of the page. + +```html + + + + 30DaysOfScript:Internal Script + + + + +``` + +This is how we write an internal script most of the time. Writing the JavaScript code in the body section is the most preferred option. Open the browser console to see the output from the `console.log()`. + +```html + + + + 30DaysOfScript:Internal Script + + + + + + +``` + +Open the browser console to see the output from the `console.log()`. + +![js code from vscode](./images/js_code_vscode.png) + +### External Script + +Similar to the internal script, the external script link can be on the header or body, but it is preferred to put it in the body. +First, we should create an external JavaScript file with .js extension. All files ending with .js extension are JavaScript files. Create a file named introduction.js inside your project directory and write the following code and link this .js file at the bottom of the body. + +```js +console.log('Welcome to 30DiasDeJavaScript') +``` + +External scripts in the _head_: + +```html + + + + 30DiasDeJavaScript:External script + + + + +``` + +External scripts in the _body_: + +```html + + + + 30DiasDeJavaScript:External script + + + + + + + +``` + +Open the browser console to see the output of the `console.log()`. + +### Multiple External Scripts + +We can also link multiple external JavaScript files to a web page. +Create a `helloworld.js` file inside the 30DaysOfJS folder and write the following code. + +```js +console.log('Hello, World!') +``` + +```html + + + + Multiple External Scripts + + + + + + +``` + +_Your main.js file should be below all other scripts_. It is very important to remember this. + +![Multiple Script](./images/multiple_script.png) + +## Introduction to Data types + +In JavaScript and also other programming languages, there are different types of data types. The following are JavaScript primitive data types: _String, Number, Boolean, undefined, Null_, and _Symbol_. + +### Numbers + +- Integers: Integer (negative, zero and positive) numbers + Example: + ... -3, -2, -1, 0, 1, 2, 3 ... +- Float-point numbers: Decimal number + Example + ... -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 ... + +### Strings + +A collection of one or more characters between two single quotes, double quotes, or backticks. + +**Example:** + +```js +'a' +'Asabeneh' +"Asabeneh" +'Finland' +'JavaScript is a beautiful programming language' +'I love teaching' +'I hope you are enjoying the first day' +`We can also create a string using a backtick` +'A string could be just as small as one character or as big as many pages' +'Any data type under a single quote, double quote or backtick is a string' +``` + +### Booleans + +A boolean value is either True or False. Any comparisons returns a boolean value, which is either true or false. + +A boolean data type is either a true or false value. + +**Example:** + +```js +true // if the light is on, the value is true +false // if the light is off, the value is false +``` + +### Undefined + +In JavaScript, if we don't assign a value to a variable, the value is undefined. In addition to that, if a function is not returning anything, it returns undefined. + +```js +let firstName +console.log(firstName) // undefined, because it is not assigned to a value yet +``` + +### Null + +Null in JavaScript means an empty value. + +```js +let emptyValue = null +``` + +## Checking Data Types + +To check the data type of a certain variable, we use the **typeof** operator. See the following example. + +```js +console.log(typeof 'Asabeneh') // string +console.log(typeof 5) // number +console.log(typeof true) // boolean +console.log(typeof null) // object type +console.log(typeof undefined) // undefined +``` + +## Comments Again + +Remember that commenting in JavaScript is similar to other programming languages. Comments are important in making your code more readable. +There are two ways of commenting: + +- _Single line commenting_ +- _Multiline commenting_ + +```js +// commenting the code itself with a single comment +// let firstName = 'Asabeneh'; single line comment +// let lastName = 'Yetayeh'; single line comment +``` + +Multiline commenting: + +```js +/* + let location = 'Helsinki'; + let age = 100; + let isMarried = true; + This is a Multiple line comment +*/ +``` + +## Variables + +Variables are _containers_ of data. Variables are used to _store_ data in a memory location. When a variable is declared, a memory location is reserved. When a variable is assigned to a value (data), the memory space will be filled with that data. To declare a variable, we use _var_, _let_, or _const_ keywords. + +For a variable that changes at a different time, we use _let_. If the data does not change at all, we use _const_. For example, PI, country name, gravity do not change, and we can use _const_. We will not use var in this challenge and I don't recommend you to use it. It is error prone way of declaring variable it has lots of leak. We will talk more about var, let, and const in detail in other sections (scope). For now, the above explanation is enough. + +A valid JavaScript variable name must follow the following rules: + +- A JavaScript variable name should not begin with a number. +- A JavaScript variable name does not allow special characters except dollar sign and underscore. +- A JavaScript variable name follows a camelCase convention. +- A JavaScript variable name should not have space between words. + +The following are examples of valid JavaScript variables. + +```js +firstName +lastName +country +city +capitalCity +age +isMarried + +first_name +last_name +is_married +capital_city + +num1 +num_1 +_num_1 +$num1 +year2020 +year_2020 +``` + +The first and second variables on the list follows the camelCase convention of declaring in JavaScript. In this material, we will use camelCase variables(camelWithOneHump). We use CamelCase(CamelWithTwoHump) to declare classes, we will discuss about classes and objects in other section. + +Example of invalid variables: + +```js + first-name + 1_num + num_#_1 +``` + +Let us declare variables with different data types. To declare a variable, we need to use _let_ or _const_ keyword before the variable name. Following the variable name, we write an equal sign (assignment operator), and a value(assigned data). + +```js +// Syntax +let nameOfVariable = value +``` + +The nameOfVriable is the name that stores different data of value. See below for detail examples. + +**Examples of declared variables** + +```js +// Declaring different variables of different data types +let firstName = 'Asabeneh' // first name of a person +let lastName = 'Yetayeh' // last name of a person +let country = 'Finland' // country +let city = 'Helsinki' // capital city +let age = 100 // age in years +let isMarried = true + +console.log(firstName, lastName, country, city, age, isMarried) +``` + +```sh +Asabeneh Yetayeh Finland Helsinki 100 true +``` + +```js +// Declaring variables with number values +let age = 100 // age in years +const gravity = 9.81 // earth gravity in m/s2 +const boilingPoint = 100 // water boiling point, temperature in °C +const PI = 3.14 // geometrical constant +console.log(gravity, boilingPoint, PI) +``` + +```sh +9.81 100 3.14 +``` + +```js +// Variables can also be declaring in one line separated by comma, however I recommend to use a seperate line to make code more readble +let name = 'Asabeneh', job = 'teacher', live = 'Finland' +console.log(name, job, live) +``` + +```sh +Asabeneh teacher Finland +``` + +When you run _index.html_ file in the 01-Day folder you should get this: + +![Day one](./images/day_1.png) + +🌕 You are amazing! You have just completed day 1 challenge and you are on your way to greatness. Now do some exercises for your brain and muscle. + +# 💻 Day 1: Exercises + +1. Write a single line comment which says, _comments can make code readable_ +2. Write another single comment which says, _Welcome to 30DiasDeJavaScript_ +3. Write a multiline comment which says, _comments can make code readable, easy to reuse_ + _and informative_ + +4. Create a variable.js file and declare variables and assign string, boolean, undefined and null data types +5. Create datatypes.js file and use the JavaScript **_typeof_** operator to check different data types. Check the data type of each variable +6. Declare four variables without assigning values +7. Declare four variables with assigned values +8. Declare variables to store your first name, last name, marital status, country and age in multiple lines +9. Declare variables to store your first name, last name, marital status, country and age in a single line +10. Declare two variables _myAge_ and _yourAge_ and assign them initial values and log to the browser console. + +```sh +I am 25 years old. +You are 30 years old. +``` + +🎉 CONGRATULATIONS ! 🎉 + +[Day 2 >>](./02_Day_Data_types/02_day_data_types.md) From d10932c12ffac4718b9691dc235e1dff7a3707b4 Mon Sep 17 00:00:00 2001 From: "diken.dev" Date: Mon, 24 Oct 2022 23:30:02 -0300 Subject: [PATCH 25/26] portuguese translation --- Portuguese/readMe.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Portuguese/readMe.md b/Portuguese/readMe.md index bfe040f..8740f20 100644 --- a/Portuguese/readMe.md +++ b/Portuguese/readMe.md @@ -37,7 +37,7 @@
    Dê suporte ao Autor para criar mais materiais educacionais
    -Paypal Logo +Paypal Logo
    @@ -74,7 +74,7 @@ [Dia 2 >>](./02_Day_Data_types/02_day_data_types.md) -![Trinta Dias de JavaScript](./images/day_1_1.png) +![Trinta Dias de JavaScript](/images/day_1_1.png) - [30 dias de JavaScript](#30-days-of-javascript) - [📔 Dia 1](#-day-1) @@ -139,11 +139,11 @@ Eu acredito que voce tem a motivação e o forte desejo de ser um desenvolvedor, Você pode não precisar do Node.js agora mas você precisará mais tarde. Instalação do [node.js](https://nodejs.org/en/). -![Node download](images/download_node.png) +![Node download](/images/download_node.png) Depois do download click duplo e intalar -![Instalação node](images/install_node.png) +![Instalação node](/images/install_node.png) Nós podemos verificar se o Node está instalador na nossa máquina local abrindo nosso terminal do dispositivo ou prompt de comando. @@ -162,13 +162,13 @@ Existe muitos navegadores por ai, Entento, Eu fortemente recomento o Google Chro Instalar o [Google Chrome](https://www.google.com.br/chrome/) se você não tem um ainda. Nós podemos escrever um pequeno código de JavaScript no console do browser, mas nós não usamos o console do navegador para desenvolver aplicações. -![Google Chrome](images/google_chrome.png) +![Google Chrome](/images/google_chrome.png) #### Abrindo o Google Chrome Console Você pode abrir o Google Chrome console por um ou outro clicando nos 3 pontos no topo do lado direito do navegador, selecionando _Mais ferramentas -> Ferramenta para desenvolvedores ou usando o atalho do teclado. Eu prefiro os atalhos. -![Abrindo o chrome](images/opening_developer_tool.png) +![Abrindo o chrome](/images/opening_developer_tool.png) Para abrir o console do Chrome usando o atalho do teclado. From ee7527e26aee75f3141805e66ed8831a873e9a95 Mon Sep 17 00:00:00 2001 From: "diken.dev" Date: Wed, 26 Oct 2022 02:07:57 -0300 Subject: [PATCH 26/26] Portuguese Translation --- Portuguese/readMe.md | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/Portuguese/readMe.md b/Portuguese/readMe.md index 8740f20..6d6b246 100644 --- a/Portuguese/readMe.md +++ b/Portuguese/readMe.md @@ -180,20 +180,16 @@ Windows/Linux: Ctl+Shift+J ``` -Windows/Linux: -Ctl+Shift+J -``` +![Abrindo o console](images/opening_chrome_console_shortcut.png) -![Opening console](images/opening_chrome_console_shortcut.png) +Depois de você abrir o console do Google Chrome, tente explorar os botões marcados. Nós vamos passar a maior parte do tempo no Console. O Console é o lugar onde vai seu código de JavaScript. O Console do Google Chrome V8 engine muda seu codigo de JavaScript para código de máquina. +Vamos escrever códigos de JavaScript no Google Chome console: -After you open the Google Chrome console, try to explore the marked buttons. We will spend most of the time on the Console. The Console is the place where your JavaScript code goes. The Google Console V8 engine changes your JavaScript code to machine code. -Let us write a JavaScript code on the Google Chrome console: +![Escrevendo codigo no console](./images/js_code_on_chrome_console.png) -![write code on console](./images/js_code_on_chrome_console.png) +#### Escrevendo Código no console do Navegador -#### Writing Code on Browser Console - -We can write any JavaScript code on the Google console or any browser console. However, for this challenge, we only focus on Google Chrome console. Open the console using: +Nós podemos escrever qualquer código de JavaScript no console do Google Chrome ou qualquer outro console de navegador, para este desafio, nós vamos focar no Console do Google Chrome. Abra o Console usando: ```sh Mac @@ -205,27 +201,34 @@ Ctl+Shift+I ##### Console.log -To write our first JavaScript code, we used a built-in function **console.log()**. We passed an argument as input data, and the function displays the output. We passed `'Hello, World'` as input data or argument in the console.log() function. +Para escrever nosso primeiro código em JavaScript, vamos usar uma função já construída chamada **console.log()**. Nós passamos um argumento como dados de input, e a função mostra o output. Nós passamos `'Olá, Mundo!'` como dados de input ou argumento na função console.log(). ```js -console.log('Hello, World!') +console.log('Olá, Mundo!') ``` -##### Console.log with Multiple Arguments +##### Console.log com Múltiplos Argumentos -The **`console.log()`** function can take multiple parameters separated by commas. The syntax looks like as follows:**`console.log(param1, param2, param3)`** +A funçao **`console.log()`** pode receber múltiplos parâmetros separados por vírgulas. A sintaxe é similar ao seguinte modo:**`console.log(param1, param2, param3)`** -![console log multiple arguments](./images/console_log_multipl_arguments.png) +![console.log com Múltiplos Argumentos](./images/console_log_multipl_arguments.png) ```js -console.log('Hello', 'World', '!') -console.log('HAPPY', 'NEW', 'YEAR', 2020) -console.log('Welcome', 'to', 30, 'Days', 'Of', 'JavaScript') +console.log('Olá', 'Mundo', '!') +console.log('Feliz', 'Ano', 'Novo', 2020) +console.log('Bem vindo', 'aos', 30, 'Dias', 'de', 'JavaScript') ``` -As you can see from the snippet code above, _`console.log()`_ can take multiple arguments. +Como você pode ver pelo trecho de código acima, _`console.log()`_ pode receber múltiplos argumentos. + +Parabéns! Você escreveu seu primeiro código de JavaScript usando _`console.log()`_. + +##### Comentários + +Nós podemos adicionar comentários para nosso código. Comentários sao importantes para fazer o codigo ser fácil de ler e deixar observações no nosso código. JavaScript nao executa o partes com comentário no nosso código. No JavaScript, qualquer linha de texto começando com // em JavaScript é um comentário, e q + + -Congratulations! You wrote your first JavaScript code using _`console.log()`_. ##### Comments