JavaScript I
(Semana 2)
MigraCode
Alexandra Yamaui
Expresiones Y Sentencias
Expresión (expression):
1 + 1; // returns 2
"hello"; // returns "hello"
2 * 4; // returns 8
"Hello" + "World"; // returns "HelloWorld"
example.js
Expresiones Y Sentencias
Expresión (expression):
function greetingPlanet() {
const planet = "Earth"; // expression
return `Hello ${planet}`; // expression
}
console.log(`2 + 4 is ${2 + 4}`); // expression
function double(num) {
return num * 2; // expression
}
example.js
Expresiones Y Sentencias
Sentencia (statement):
const sum = 1 + 1; // action: assigns result of `1 + 1` to variable `sum`
const greeting = "hello"; // action: assigns result of the expression "hello" to variable `greeting`
console.log(2 * 4); // action: logs the result of `2 * 4` to the console
sayGreeting(greeting); // action: calls the function `sayGreeting` with the parameter `greeting`
example.js
Ejercicios
Ejercicio A (5 mins)
En el terminal de VS Code, ejecuta el comando node y ejecuta las siguientes expresiones. Cual es el resultado? Hay algo que te parezca inesperado? (Para salir del node REPL, tienes que presionar Ctrl+d o Cmd+D en Mac)
Tipos de datos
Booleanos
let codeYourFutureIsGreat = true;
let thisIsATerribleClass = false;
example.js
Booleanos
Booleano:
Boolean(100); // true
Boolean(3.14); // true
Boolean(-15); // true
Boolean("Hello"); // true
Boolean("false"); // true
Boolean(7 + 1 + 3.14); // true
Boolean(""); // false
Boolean(0); // false
Boolean(undefined); // false
Boolean(null); // false
example.js
Operadores de comparación
Comparación:
Operadores de comparación (Ejercicio: let x = 5;)
== | igualdad en valor | x == 8 | false |
| | x == 5 | true |
| | x == "5" | true ! |
=== | igualdad en valor y tipo | x === 5 | true |
| | x === "5" | false |
!= | desigualdad en valor | x != 8 | true |
| | x != "5" | false ! |
!== | desigualdad en valor o tipo | x !== 5 | false |
| | x !== "5" | true |
> | mayor que | 8 > x | true |
< | menor que | x < 8 | true |
>= | mayor o igual que | 5 >= x | true |
<= | menor o igual que | 2 <= x | true |
Condicionales
let isHappy = true;
// The condition is an expression that returns true or false
if (isHappy) {
console.log("I am happy");
}
console.log("End of script");
// output ?
example.js
Condicionales
let isHappy = true;
// The condition is an expression that returns true or false
if (isHappy) {
console.log("I am happy");
}
console.log("End of script");
// output
I am happy
End of script
example.js
Condicionales
// boolean expression (returns a boolean value)
if ((1 + 1) === 2) {
// do something
}
// boolean expression (returns a boolean value)
if (10 < 5) {
// do something
}
example.js
Ejercicios
Ejercicio B (10 mins)
function boolChecker(bool) {
if (typeof bool === ?) {
return "You've given me a bool, thanks!";
}
return "No bool, not cool.";
}
boolChecker(true);
boolChecker(2);
Condicionales
let isHappy = true;
// The condition is met
if (isHappy) {
console.log("I am happy :)");
} else { // the condition is not met
console.log("I am not happy :(");
}
console.log("End of script");
// output?
example.js
Condicionales
example.js
let isHappy = true;
// The condition is met
if (isHappy) {
console.log("I am happy :)");
} else { // the condition is not met
console.log("I am not happy :(");
}
console.log("End of script");
// output
I am happy :)
End of script
Condicionales
let age = 24;
if (age >= 65) {
console.log("John is an old guy.");
} else if (age < 18) {
console.log("John is a young boy.");
} else {
console.log("John is an adult.");
}
example.js
Ejercicios
Ejercicio C (5 mins)
function numberChecker(num) {
if (num > 20) {
return `${num} is greater than 20`;
} else if (num !== 20) {
return `${num} is equal to 20`;
} else if (num < 20) {
return `${num} is less than 20`;
} else if (num < 0) {
return `${num} is less than 0`;
} else {
return `${num} isn't even a number :(`;
}
}
Ejercicios
Ejercicio D (10 mins)
Crea una función que retorne un mensaje dependiendo de tu estado de ánimo! La función debe:
Operadores Lógicos
// AND operator
&&
// OR operator
||
// NOT operator
!
example.js
Expresiones Lógicas
// AND operator
expr1 && expr2
// OR operator
expr1 || expr2
// NOT operator
!expr
example.js
Operadores Lógicos
Operadores lógicos:
let num = 10;
function satisfiesRequirements(num) {
if (num > 3 && num < 10) {
return true;
} else if (1 || 12) {
return true;
}
return false;
}
satisfiesRequirements(num); // output ?
example.js
Operadores Lógicos
Operadores lógicos:
let num = 10;
function satisfiesRequirements(num) {
if (num > 3 && num < 10) {
return true;
} else if (1 || 12) {
return true;
}
return false;
}
satisfiesRequirements(num); // output: true
example.js
Expresiones Lógicas
Evaluación corto-circuito:
let num = 10;
function satisfiesRequirements(num) {
if (n > 3 || (n < 10 && n > 8)) {
return true;
}
return false;
}
satisfiesRequirements(5);
example.js
Expresiones Lógicas
OR:
(Recuerda que todo lo que tenga un valor evalúa a true)
let o1 = true || true; // ?
let o2 = false || true; // ?
let o3 = true || false; // ?
let o4 = false || 3 === 4; // ?
let o5 = "Cat" || "Dog"; // ?
let o6 = false || "Cat"; // ?
let o7 = "Cat" || false; // ?
example.js
Expresiones Lógicas
OR:
(Recuerda que todo lo que tenga un valor evalúa a true)
let o1 = true || true; // t || t returns true
let o2 = false || true; // f || t returns true
let o3 = true || false; // t || f returns true
let o4 = false || 3 === 4; // f || f returns false
let o5 = "Cat" || "Dog"; // t || t returns Cat
let o6 = false || "Cat"; // f || t returns Cat
let o7 = "Cat" || false; // t || f returns Cat
example.js
Expresiones Lógicas
AND:
(Recuerda que todo lo no que tenga un valor evalúa a false)
let a1 = true && true; // ?
let a2 = true && false; // ?
let a3 = false && true; // ?
let a4 = false && 3 === 4; // ?
let a5 = "Cat" && "Dog"; // ?
let a6 = false && "Cat"; // ?
let a7 = "Cat" && false; // ?
example.js
Expresiones Lógicas
AND:
(Recuerda que todo lo no que tenga un valor evalúa a false)
let a1 = true && true; // t && t returns true
let a2 = true && false; // t && f returns false
let a3 = false && true; // f && t returns false
let a4 = false && 3 === 4; // f && f returns false
let a5 = "Cat" && "Dog"; // t && t returns Dog
let a6 = false && "Cat"; // f && t returns false
let a7 = "Cat" && false; // t && f returns false
example.js
Expresiones Lógicas
NOT:
let n1 = !true; // !t returns false
let n2 = !false; // !f returns true
let n3 = !"Cat"; // !t returns false
example.js
Ejercicios
Ejercicio E (5 mins)
Escribe las siguientes expresiones en node REPL y ve el resultado. Encuentras algún valor inesperado?
Loops
console.log("The count is 1");
console.log("The count is 2");
console.log("The count is 3");
console.log("The count is 4");
console.log("The count is 5");
// ...
console.log("The count is 100");
example.js
Loops
Loops (iteradores):
Permiten ejecutar el mismo código múltiples veces con valores diferentes
console.log("The count is 1");
console.log("The count is 2");
console.log("The count is 3");
console.log("The count is 4");
console.log("The count is 5");
// ...
console.log("The count is 100");
example.js
Loops
Loops (iteradores):
Permiten ejecutar el mismo código múltiples veces con valores diferentes.
Cada vuelta se llama iteración
console.log("The count is 1");
console.log("The count is 2");
console.log("The count is 3");
console.log("The count is 4");
console.log("The count is 5");
// ...
console.log("The count is 100");
example.js
Loops
while loops:
let count = 1; // counter
while (count <= 100) {
console.log("The count is: " + count);
count += 1; // This is the same as count = count + 1
}
….
The count is: 1
The count is: 2
The count is: 3
example.js
Ejercicios
Ejercicio G (10 mins)
const apolloCountdownMessage = "all engine running… LIFT-OFF!";
let countdown = 8;
console.log(apolloCountdownMessage);
// Expected output
8
7
6
5
4
3
2
1
0
all engine running... LIFT-OFF!
Loops
for loops:
for (initialization; condition; final-expression) { ... }
for (let i=1; i < 20; i += 1) {...}
example.js
Start counter at 0
Checks condition
On each loop increment the counter by 1
Loops
for loop:
for (let i = 0; i < 100; i++) {
console.log("The count is: " + counter);
}
let i = 0;
while (i < 100) {
…
i = i + 1;
}
// i++ is a shortcut for i = i + 1
// sames as i += 1
example.js
Ejercicios
Ejercicio H (10 mins)
Calcular el exponencial de los números pares del 5 al 20 usando un for loop y las funciones provistas.
function exponential(number) {
return number * number;
}
function esPar(number) {
return number % 2 === 0;
} // devuelve booleano
// Expected output
The exponential of 6 is 36
The exponential of 8 is 64
The exponential of 10 is 100
The exponential of 12 is 144
The exponential of 14 is 196
The exponential of 16 is 256
The exponential of 18 is 324
Arreglos
const mentor1 = "Daniel";
const mentor2 = "Irina";
const mentor3 = "Rares";
example.js
Arreglos
const mentor1 = "Daniel";
const mentor2 = "Irina";
const mentor3 = "Rares";
const mentors = ["Daniel", "Irina", "Rares"];
example.js
Arreglos
const mentor1 = "Daniel";
const mentor2 = "Irina";
const mentor3 = "Rares";
const mentors = ["Daniel", "Irina", "Rares"];
example.js
Arreglos
const mentor1 = "Daniel";
const mentor2 = "Irina";
const mentor3 = "Rares";
const mentors = ["Daniel", "Irina", "Rares"];
const testScores = [16, 49, 85];
const grades = ["F", "D", "A"];
const greetings = ["Hello, how are you?", "Hi! Nice to meet you!"];
const mix = [true, "ABC", 36]; // try to avoid arrays of different data types
example.js
Arreglos
Cómo acceder a los valores de un arreglo?
const students = ["Ahmed", "Maria", "Atanas", "Nahidul", "Jack"];
students[0]; // "Ahmed"
students[2]; // "Atanas"
students[3]; // "Nahidul"
students[1] // “Maria”
example.js
Arreglos
Cómo modificar elementos en un arreglo?
let students = ["Ahmed", "Maria", "Atanas", "Nahidul", "Jack"];
students[2] = "Bianca";
console.log(students); // ["Ahmed", "Maria", "Bianca", "Nahidul", "Jack"]
let jaime = "Jaime";
jaime = 23;
example.js
Ejercicios
Ejercicio I (5 mins)
En el node REPL, ingresa el siguiente arreglo:
const fruits = ['banana', 'apple', 'strawberry', 'kiwi', 'fig', 'orange'];
Ahora, usando los índices correctos, obtén los siguientes valores:
Luego, reemplaza 'apple' con 'raspberry', y reemplaza 'fig' con 'pineapple'.
Ejercicios
Ejercicio J (5 mins)
Completa la siguiente función tal que si la segunda posición del arreglo contiene el nombre "Amy" retorne "Second index matched!"
function secondMatchesAmy(array) {
if (?) {
return "Second index matched!";
}
return "Second index not matched";
}
let names = ["Alex", "Amara", "Carlos"];
let names2 = ["Ali", "Amy", "Naresh"];
const result = secondMatchesAmy(names);
console.log(result)
Arreglos
Iterando un arreglo
const daysOfWeek = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
];
for (let i = 0; i < daysOfWeek.length; i++) {
const dayMessage = "day is: " + daysOfWeek[i];
const indexMessage = "index is: " + i;
console.log(indexMessage, dayMessage);
}
example.js
Ejercicios
Ejercicio K (10 mins)
Escribe una función que reciba un arreglo de estudiantes. En la función, usa un for loop para iterar sobre el arreglo e imprimir el nombre de cada estudiante.
Strings - arreglos
Strings
const greeting = "Hola, I’m Alexandra";
for (let i = 0; i < greeting.length; i++) {
console.log(greeting[i]);
}
// output?
example.js
Ejercicio
Ejercicio F (modificado) (15 mins)
Escribe una función que revise si un nombre de usuario tiene un formato y un tipo de usuario adecuado.La función debe:
Ejercicio
Ejercicio F (15 mins)
Escribe una función que revise si un nombre de usuario tiene un formato y un tipo de usuario adecuado.La función debe:
Nota: para transformar una letra a mayúscula o minúscula puedes usar las funciones toLowerCase() y toUpperCase()