├── exercises ├── 01-Hello_World │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 03-Multiply_two_values │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 23-Bottles_of_milk │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 22-The_Beatles │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 16-Your_first_loop │ ├── app.js │ ├── solution.hide.js │ ├── tests.js │ ├── README.md │ └── README.es.md ├── 05-Constants │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 17-Create_a_for_loop │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 04-User_inputed_variables │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 11-Your_first_if │ ├── app.js │ ├── solution.hide.js │ ├── README.es.md │ ├── README.md │ └── tests.js ├── 20-Looping_with_FizzBuzz │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 02-Print_variables_in_the_console │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 08-Calling_your_first_function │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 15-Rand_from_one_to_six │ ├── app.js │ ├── solution.hide.js │ ├── README.es.md │ ├── README.md │ └── tests.js ├── 14-Random_numbers │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 06-String_concatenation │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 09-Creating_your_first_function │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── tests.js │ └── README.es.md ├── 10-Create_a_new_function │ ├── app.js │ ├── solution.hide.js │ ├── test.js │ ├── README.md │ └── README.es.md ├── 18-While_loop │ ├── app.js │ ├── solution.hide.js │ ├── tests.js │ ├── README.md │ └── README.es.md ├── 12-How_much_the_wedding_costs │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 07-Create_a_basic_HTML │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 13-Your_first_switch │ ├── app.js │ ├── tests.js │ ├── solution.hide.js │ ├── README.md │ └── README.es.md ├── 00-Welcome │ ├── README.md │ └── README.es.md ├── 21-Russian_Roulette │ ├── app.js │ ├── solution.hide.js │ ├── README.md │ ├── README.es.md │ └── tests.js ├── 19-Random_colors_loop │ ├── app.js │ ├── solution.hide.js │ ├── tests.js │ ├── README.md │ └── README.es.md └── 24-Javascript_Objects │ ├── app.js │ ├── tests.js │ ├── solution.hide.js │ ├── README.md │ └── README.es.md ├── preview.png ├── js-bg-badge.png ├── .learn └── assets │ └── i-love-javascript.jpeg ├── .gitpod.Dockerfile ├── .vscode └── settings.json ├── .gitignore ├── .gitpod.yml ├── .github └── workflows │ └── learnpack-audit.yml ├── LICENSE.md ├── .devcontainer └── devcontainer.json ├── learn.json ├── README.md └── README.es.md /exercises/01-Hello_World/app.js: -------------------------------------------------------------------------------- 1 | //your code below 2 | -------------------------------------------------------------------------------- /exercises/03-Multiply_two_values/app.js: -------------------------------------------------------------------------------- 1 | // Your code below: -------------------------------------------------------------------------------- /exercises/23-Bottles_of_milk/app.js: -------------------------------------------------------------------------------- 1 | // Your code here: 2 | -------------------------------------------------------------------------------- /exercises/01-Hello_World/solution.hide.js: -------------------------------------------------------------------------------- 1 | console.log("Hello World") -------------------------------------------------------------------------------- /exercises/22-The_Beatles/app.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | //Your code above ^^^ 4 | 5 | console.log(sing()); -------------------------------------------------------------------------------- /exercises/16-Your_first_loop/app.js: -------------------------------------------------------------------------------- 1 | for (let i = 0; i < 100; i++) { 2 | console.log(i) 3 | } 4 | -------------------------------------------------------------------------------- /exercises/05-Constants/app.js: -------------------------------------------------------------------------------- 1 | const VERSION = '0.1'; 2 | 3 | VERSION = '0.9'; 4 | 5 | console.log(VERSION); -------------------------------------------------------------------------------- /exercises/17-Create_a_for_loop/app.js: -------------------------------------------------------------------------------- 1 | // Declare and write your function here: 2 | 3 | 4 | standardsMaker(); -------------------------------------------------------------------------------- /preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/HEAD/preview.png -------------------------------------------------------------------------------- /exercises/04-User_inputed_variables/app.js: -------------------------------------------------------------------------------- 1 | let age = prompt('What is your age?'); 2 | 3 | // Your code below: 4 | -------------------------------------------------------------------------------- /exercises/11-Your_first_if/app.js: -------------------------------------------------------------------------------- 1 | let total = prompt('How many km are left to go?'); 2 | 3 | // Your code below: 4 | -------------------------------------------------------------------------------- /exercises/20-Looping_with_FizzBuzz/app.js: -------------------------------------------------------------------------------- 1 | function fizzBuzz() { 2 | // Your code here 3 | } 4 | 5 | fizzBuzz(); -------------------------------------------------------------------------------- /js-bg-badge.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/HEAD/js-bg-badge.png -------------------------------------------------------------------------------- /exercises/05-Constants/solution.hide.js: -------------------------------------------------------------------------------- 1 | // const VERSION = '0.1'; 2 | 3 | const VERSION = '0.9'; 4 | 5 | console.log(VERSION); -------------------------------------------------------------------------------- /exercises/03-Multiply_two_values/solution.hide.js: -------------------------------------------------------------------------------- 1 | // Your code below: 2 | let variablesAreCool=2345*7323 3 | console.log(variablesAreCool) -------------------------------------------------------------------------------- /exercises/02-Print_variables_in_the_console/app.js: -------------------------------------------------------------------------------- 1 | let mySuperVariable = 'hello'; 2 | console.log(mySuperVariable); 3 | 4 | // your code below 5 | -------------------------------------------------------------------------------- /exercises/08-Calling_your_first_function/app.js: -------------------------------------------------------------------------------- 1 | function isOdd(myNumber) 2 | { 3 | return !(myNumber % 2 == 0); 4 | } 5 | 6 | // Your code below: 7 | isOdd() -------------------------------------------------------------------------------- /.learn/assets/i-love-javascript.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/HEAD/.learn/assets/i-love-javascript.jpeg -------------------------------------------------------------------------------- /exercises/16-Your_first_loop/solution.hide.js: -------------------------------------------------------------------------------- 1 | /* Done - check tests and clear for student use */ 2 | 3 | for (let i = 0; i <= 100; i++) { 4 | console.log(i) 5 | } -------------------------------------------------------------------------------- /exercises/15-Rand_from_one_to_six/app.js: -------------------------------------------------------------------------------- 1 | function getRandomInt() 2 | { 3 | let randomNumber = Math.random(); 4 | return randomNumber; 5 | } 6 | console.log(getRandomInt()); -------------------------------------------------------------------------------- /exercises/14-Random_numbers/app.js: -------------------------------------------------------------------------------- 1 | function getRandomInt() 2 | { 3 | let randomNumber = Math.random(); 4 | return randomNumber; 5 | } 6 | 7 | 8 | console.log(getRandomInt()); 9 | -------------------------------------------------------------------------------- /exercises/04-User_inputed_variables/solution.hide.js: -------------------------------------------------------------------------------- 1 | let age = prompt('What is your age?'); 2 | 3 | // Your code below: 4 | 5 | let result = parseInt(age) + 10 6 | console.log(result); -------------------------------------------------------------------------------- /exercises/08-Calling_your_first_function/solution.hide.js: -------------------------------------------------------------------------------- 1 | function isOdd(myNumber) 2 | { 3 | return !(myNumber % 2 == 0); 4 | } 5 | 6 | // Your code below: 7 | console.log(isOdd(45345)) -------------------------------------------------------------------------------- /exercises/02-Print_variables_in_the_console/solution.hide.js: -------------------------------------------------------------------------------- 1 | let mySuperVariable = 'hello'; 2 | console.log(mySuperVariable); 3 | 4 | // your code below 5 | let color = 'red'; 6 | console.log(color) -------------------------------------------------------------------------------- /exercises/15-Rand_from_one_to_six/solution.hide.js: -------------------------------------------------------------------------------- 1 | function getRandomInt() 2 | { 3 | let randomNumber = Math.floor(Math.random() * 6) + 1; 4 | return randomNumber; 5 | } 6 | console.log(getRandomInt()); -------------------------------------------------------------------------------- /exercises/14-Random_numbers/solution.hide.js: -------------------------------------------------------------------------------- 1 | function getRandomInt() 2 | { 3 | let randomNumber = Math.floor(Math.random() * 10) + 1; 4 | return randomNumber; 5 | } 6 | 7 | 8 | console.log(getRandomInt()); 9 | -------------------------------------------------------------------------------- /exercises/06-String_concatenation/app.js: -------------------------------------------------------------------------------- 1 | //Set the values here 2 | let myVar1 = ''; 3 | let myVar2 = ''; 4 | 5 | //Don't change any code below 6 | let theNewString = myVar1+' '+myVar2; 7 | console.log(theNewString); -------------------------------------------------------------------------------- /exercises/09-Creating_your_first_function/app.js: -------------------------------------------------------------------------------- 1 | function addNumbers(a,b){ 2 | // This is the function's body. Write your code here. 3 | 4 | } 5 | 6 | //Do not change the code below 7 | console.log(addNumbers(3,4)); 8 | -------------------------------------------------------------------------------- /.gitpod.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-full:latest 2 | 3 | USER gitpod 4 | 5 | RUN npm i jest@29.7.0 jest-environment-jsdom@29.7.0 -g 6 | RUN npm i @learnpack/learnpack@4.0.8 -g && learnpack plugins:install @learnpack/node@1.1.13 7 | -------------------------------------------------------------------------------- /exercises/06-String_concatenation/solution.hide.js: -------------------------------------------------------------------------------- 1 | //Set the values here 2 | let myVar1 = 'Hello'; 3 | let myVar2 = 'World'; 4 | 5 | //Don't change any code below 6 | let theNewString = myVar1+' '+myVar2; 7 | console.log(theNewString); -------------------------------------------------------------------------------- /exercises/09-Creating_your_first_function/solution.hide.js: -------------------------------------------------------------------------------- 1 | function addNumbers(a,b){ 2 | // This is the function's body. Write your code here. 3 | return a + b 4 | } 5 | 6 | //Do not change the code below 7 | console.log(addNumbers(3,4)); 8 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.autoSave": "afterDelay", 3 | "files.autoSaveDelay": 700, 4 | "editor.minimap.enabled": false, 5 | "workbench.editorAssociations": { 6 | "*.md": "vscode.markdown.preview.editor" 7 | } 8 | } -------------------------------------------------------------------------------- /exercises/10-Create_a_new_function/app.js: -------------------------------------------------------------------------------- 1 | function shortIntroduction() { 2 | // Complete this function's body and arguments 3 | 4 | } 5 | 6 | // Fill the gaps with your data in the correct order 7 | console.log(shortIntroduction(" ", " ", " ")) -------------------------------------------------------------------------------- /exercises/18-While_loop/app.js: -------------------------------------------------------------------------------- 1 | //fix this function: 2 | function startCounting() { 3 | let counter = 100; 4 | while (counter <= 100) { 5 | counter--; 6 | console.log(counter); 7 | } 8 | 9 | return counter; 10 | } 11 | 12 | startCounting(); -------------------------------------------------------------------------------- /exercises/17-Create_a_for_loop/solution.hide.js: -------------------------------------------------------------------------------- 1 | // Declare and write your function here: 2 | function standardsMaker() { 3 | for (let i = 0; i < 300; i++) { 4 | console.log("I will write questions if I'm stuck") 5 | } 6 | } 7 | 8 | standardsMaker(); -------------------------------------------------------------------------------- /exercises/18-While_loop/solution.hide.js: -------------------------------------------------------------------------------- 1 | //fix this function: 2 | function startCounting() { 3 | let counter = 101; 4 | while (counter > 0) { 5 | counter--; 6 | console.log(counter); 7 | } 8 | 9 | return counter; 10 | } 11 | 12 | startCounting(); -------------------------------------------------------------------------------- /exercises/12-How_much_the_wedding_costs/app.js: -------------------------------------------------------------------------------- 1 | let guests = prompt('How many people are coming to your wedding?'); 2 | 3 | function getPrice(guests){ 4 | let cost = 0; 5 | // Your code here 6 | 7 | 8 | return cost; 9 | } 10 | 11 | let price = getPrice(guests); 12 | console.log('Your wedding will cost '+price+' dollars'); 13 | -------------------------------------------------------------------------------- /exercises/20-Looping_with_FizzBuzz/solution.hide.js: -------------------------------------------------------------------------------- 1 | function fizzBuzz() { 2 | // Your code here 3 | for (let i = 1; i < 101; i++) { 4 | if (i % 15 == 0) console.log("FizzBuzz"); 5 | else if (i % 3 == 0) console.log("Fizz"); 6 | else if (i % 5 == 0) console.log("Buzz"); 7 | else console.log(i); 8 | } 9 | } 10 | 11 | fizzBuzz(); -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | /* 3 | 4 | !.gitignore 5 | !.gitpod.yml 6 | !.gitpod.Dockerfile 7 | !bc.json 8 | !learn.json 9 | !README.md 10 | !README.es.md 11 | !.vscode 12 | 13 | !/exercises 14 | !/exercises/* 15 | 16 | !/.learn 17 | /.learn/** 18 | !/.learn/resets 19 | !/.learn/resets/** 20 | !/.learn/assets 21 | !/.learn/assets/** 22 | -------------------------------------------------------------------------------- /exercises/07-Create_a_basic_HTML/app.js: -------------------------------------------------------------------------------- 1 | const a = ''; 2 | const b = ''; 3 | const c = ''; 4 | const d = ''; 5 | const e = ''; 6 | const f = ''; 7 | const g = ''; 8 | const h = '<body>'; 9 | 10 | //Modify this variable 11 | let htmlDocument = 'e+c+g+h+d+a+f+b'; 12 | 13 | console.log(htmlDocument); -------------------------------------------------------------------------------- /exercises/07-Create_a_basic_HTML/solution.hide.js: -------------------------------------------------------------------------------- 1 | const a = ''; 2 | const b = ''; 3 | const c = ''; 4 | const d = ''; 5 | const e = ''; 6 | const f = ''; 7 | const g = ''; 8 | const h = '<body>'; 9 | 10 | //Modify this variable 11 | let htmlDocument = e+c+g+a+f+h+d+b; 12 | 13 | console.log(htmlDocument); -------------------------------------------------------------------------------- /exercises/11-Your_first_if/solution.hide.js: -------------------------------------------------------------------------------- 1 | let total = prompt('How many km are left to go?'); 2 | 3 | // Your code below: 4 | 5 | if (total <= 50) { 6 | console.log("I'm parking. I'll see you right now"); 7 | } else if (total <= 100) { 8 | console.log("We'll be there in 5 minutes"); 9 | } else { 10 | console.log("We still have a bit of driving left to go"); 11 | } 12 | -------------------------------------------------------------------------------- /exercises/10-Create_a_new_function/solution.hide.js: -------------------------------------------------------------------------------- 1 | function shortIntroduction(name, profession, age) { 2 | // Complete this function's body and arguments 3 | return "Hello! my name is " + name + ", my profession is " + profession + ". I am " + age + " years old." 4 | } 5 | 6 | // Fill the gaps with your data in the correct order 7 | console.log(shortIntroduction("Trinity", "Developer", "35")) -------------------------------------------------------------------------------- /exercises/22-The_Beatles/solution.hide.js: -------------------------------------------------------------------------------- 1 | function sing(){ 2 | let str = ""; 3 | for(let i = 0; i < 11; i++){ 4 | if(i === 4) str += 'there will be an answer, '; 5 | else if (i === 10) str += 'whisper words of wisdom, let it be'; 6 | else str += 'let it be, '; 7 | } 8 | return str; 9 | } 10 | 11 | //Your code above ^^^ 12 | 13 | console.log(sing()); 14 | -------------------------------------------------------------------------------- /exercises/15-Rand_from_one_to_six/README.es.md: -------------------------------------------------------------------------------- 1 | # `15` Random numbers from one to six 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. ¡Bien! Ahora cambia lo que sea que necesites cambiar para hacer que el algoritmo imprima números enteros aleatorios entre 1 y 6. 6 | 7 | ## 💡 Pistas: 8 | 9 | + Debería imprimir entre 1 y 6, no entre 0 y 6. 10 | 11 | + Este ejercicio es super sencillo, no te compliques... -------------------------------------------------------------------------------- /exercises/15-Rand_from_one_to_six/README.md: -------------------------------------------------------------------------------- 1 | # `15` Random numbers from one to six 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Okay! Now change whatever you need to change in order to make the algorithm print random integers between 1 and 6. 6 | 7 | ## 💡 Hints: 8 | 9 | + It should print between 1 and 6, not between 0 and 6. 10 | 11 | + This exercise is super simple, don't overcomplicate things... 12 | -------------------------------------------------------------------------------- /exercises/13-Your_first_switch/app.js: -------------------------------------------------------------------------------- 1 | function getColor(selection) 2 | { 3 | switch(selection){ 4 | // Add more options here 5 | default: 6 | return false; //returns false because the user picked an unavailable color 7 | break; 8 | } 9 | } 10 | 11 | let colorname = prompt('What color do you want?').trim(); 12 | let isAvailable = getColor(colorname); 13 | 14 | if(isAvailable) 15 | console.log('Good news! That color is available'); 16 | else 17 | console.log('We are sorry, that color is not available'); 18 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: 2 | file: .gitpod.Dockerfile 3 | 4 | ports: 5 | - port: 3000 6 | onOpen: ignore 7 | 8 | vscode: 9 | extensions: 10 | - learn-pack.learnpack-vscode 11 | 12 | github: 13 | prebuilds: 14 | # enable for the master/default branch (defaults to true) 15 | master: true 16 | # enable for pull requests coming from this repo (defaults to true) 17 | pullRequests: false 18 | # add a "Review in Gitpod" button as a comment to pull requests (defaults to true) 19 | addComment: false -------------------------------------------------------------------------------- /exercises/12-How_much_the_wedding_costs/solution.hide.js: -------------------------------------------------------------------------------- 1 | let guests = prompt('How many people are coming to your wedding?'); 2 | 3 | function getPrice(guests){ 4 | let cost = 0; 5 | // Your code here 6 | if (guests <= 50) { 7 | cost = 4000 8 | }else if(guests <=100){ 9 | cost = 10000 10 | }else if (guests <=200 ){ 11 | cost = 15000 12 | }else { 13 | cost = 20000 14 | } 15 | 16 | return cost; 17 | } 18 | 19 | let price = getPrice(guests); 20 | console.log('Your wedding will cost '+price+' dollars'); -------------------------------------------------------------------------------- /exercises/02-Print_variables_in_the_console/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=3LDGpTlLe_w" 3 | --- 4 | 5 | # `02` Print Variables to the Console 6 | 7 | You can also use the `console.log()` function to print variables in the console. It is a great way to know their content, like this: 8 | 9 | ## 📝 Instructions: 10 | 11 | 1. Declare a new variable called `color` and assign the value `"red"` to it. 12 | 13 | 2. Print its value to the console. 14 | 15 | ## 📎 Example: 16 | 17 | ```js 18 | let mySuperVariable = 'hello'; 19 | console.log(mySuperVariable); 20 | ``` 21 | -------------------------------------------------------------------------------- /exercises/02-Print_variables_in_the_console/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=49LFfe9Du58" 3 | --- 4 | 5 | # `02` Print Variables to the Console 6 | 7 | También puedes utilizar la función `console.log()` para imprimir variables en la consola. Es una buena forma para saber su contenido. 8 | 9 | ## 📝 Instrucciones: 10 | 11 | 1. Declara una nueva variable llamada `color` y asígnale el valor `"red"`. 12 | 13 | 2. Luego, imprime su valor en la consola. 14 | 15 | ## 📎 Ejemplo: 16 | 17 | ```js 18 | let mySuperVariable = 'hello'; 19 | console.log(mySuperVariable); 20 | ``` 21 | -------------------------------------------------------------------------------- /exercises/00-Welcome/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | intro: "https://www.youtube.com/watch?v=GjQEotj3t6Y" 3 | --- 4 | 5 | ![Javascript Preview](../../.learn/assets/i-love-javascript.jpeg?raw=true) 6 | 7 | # Welcome to the JavaScript Exercises! 8 | 9 | This is the first in a series of interactive tutorials meant to provide everything you need to start your journey into the world of JavaScript. 10 | 11 | ## You will learn: 12 | 13 | - `console.log()` 14 | - String concatenation 15 | - Arrays 16 | - Functions 17 | - Loops 18 | - And much more! 19 | 20 | Click `Next →` on the top right side of the screen when you are ready to start. 21 | -------------------------------------------------------------------------------- /exercises/21-Russian_Roulette/app.js: -------------------------------------------------------------------------------- 1 | // firePosition will be the position in which the gun will fire. 2 | let firePosition = 1; 3 | 4 | // The output of spinChamber will be a number and it can be passed as a parameter to the fireGun function. 5 | const spinChamber = () => { 6 | let chamberPosition = Math.floor((Math.random() * 6) + 1); 7 | return chamberPosition; 8 | }; 9 | 10 | // Remove the // below and complete the commented lines 11 | const fireGun = (bulletPosition) => { 12 | // if (... === firePosition) return ("You're dead!"); 13 | // else return ("Keep playing!"); 14 | }; 15 | 16 | console.log(fireGun(spinChamber())); 17 | -------------------------------------------------------------------------------- /exercises/19-Random_colors_loop/app.js: -------------------------------------------------------------------------------- 1 | function getColor(colorNumber = 0) { 2 | //make sure the parameter is a number and not a string by converting the value to int: 3 | colorNumber = parseInt(colorNumber); 4 | switch (colorNumber) { 5 | case 1: return "red"; 6 | 7 | case 2: return "yellow"; 8 | 9 | case 3: return "blue"; 10 | 11 | case 4: return "green"; 12 | 13 | default: return "black"; 14 | 15 | } 16 | } 17 | 18 | function getAllStudentColors() { 19 | 20 | //your loop here 21 | let exampleColor = getColor(1); 22 | } 23 | 24 | //call the function below with the number of students in the class and print on the console 25 | getAllStudentColors(); 26 | 27 | -------------------------------------------------------------------------------- /exercises/21-Russian_Roulette/solution.hide.js: -------------------------------------------------------------------------------- 1 | // firePosition will be the position in which the gun will fire. 2 | let firePosition = 1; 3 | 4 | // The output of spinChamber will be a number and it can be passed as a parameter to the fireGun function. 5 | const spinChamber = () => { 6 | let chamberPosition = Math.floor((Math.random() * 6) + 1); 7 | return chamberPosition; 8 | }; 9 | 10 | // Remove the // below and complete the commented lines 11 | const fireGun = (bulletPosition) => { 12 | if (bulletPosition === firePosition) { 13 | return ("You're dead!"); 14 | } 15 | else return ("Keep playing!"); 16 | }; 17 | 18 | console.log(fireGun(spinChamber())); 19 | -------------------------------------------------------------------------------- /exercises/00-Welcome/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | intro: "https://www.youtube.com/watch?v=32WbSowUcjc" 3 | --- 4 | 5 | ![Javascript Preview](../../.learn/assets/i-love-javascript.jpeg?raw=true) 6 | 7 | # Bienvenido a los Ejercicios de JavaScript! 8 | 9 | Este es el primero de una serie de tutoriales interactivos orientados a entregarte todos los conocimientos necesarios para tener éxito en el mundo de JavaScript. 10 | 11 | ## Aprenderás: 12 | 13 | - `console.log` 14 | - Concatenación de string 15 | - Arrays 16 | - Funciones 17 | - Loops 18 | - ¡Y mucho más! 19 | 20 | Presiona el botón de `Next →` en la esquina superior derecha de la pantalla cuando estés listo para empezar los ejercicios. 21 | -------------------------------------------------------------------------------- /exercises/03-Multiply_two_values/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=0AstdiXq3sM" 3 | --- 4 | 5 | # `03` Multiply Two Values 6 | 7 | Programming languages, such as JavaScript, allow for basic math operations (multiplication, division, etc.) to be performed on expressions. 8 | 9 | To multiply two values in JavaScript, use the asterisk (*) operator like this: 10 | 11 | ```js 12 | let resultingValue = 2 * 3; 13 | ``` 14 | 15 | In this instance, we stored the product of `2 * 3` into a variable called `resultingValue`. 16 | 17 | ## 📝 Instructions: 18 | 19 | 1. Store the product of 2345 times 7323 in a variable called `variablesAreCool`. 20 | 21 | 2. Print the result to the console. 22 | -------------------------------------------------------------------------------- /exercises/07-Create_a_basic_HTML/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=5NDv7NnSy6M" 3 | --- 4 | 5 | # `07` Creating Basic HTML Code 6 | 7 | Let's continue using string concatenation to generate HTML. The code on the left contains 8 constants with different string values: 8 | 9 | ## 📝 Instructions: 10 | 11 | 1. Combine the constants given using string concatenation. 12 | 13 | 2. Assign the value of the variable `htmlDocument` to this new string (This is the template of a typical HTML document with the HTML tags in the right order). 14 | 15 | 3. Print the value of `htmlDocument` to the console. 16 | 17 | ## 💡 Hint: 18 | 19 | + The output should look like this: 20 | 21 | ```js 22 | <html><head><title> 23 | ``` 24 | -------------------------------------------------------------------------------- /exercises/03-Multiply_two_values/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=PICBpE3fuNY" 3 | --- 4 | 5 | # `03` Multiply Two Values 6 | 7 | Los lenguajes de programación, tales como JavaScript, te permiten hacer operaciones matemáticas básicas (multiplicación, división, etc.) a ejecutarse en expresiones. 8 | 9 | Para multiplicar 2 valores en JavaScript, debes utilizar el asterisco (*) de esta forma: 10 | 11 | ```js 12 | let resultingValue = 2 * 3; 13 | ``` 14 | 15 | En esta instancia, estamos guardando el producto de multiplicar `2 * 3` dentro de una variable llamada `resultingValue`. 16 | 17 | ## 📝 Instrucciones: 18 | 19 | 1. Por favor, guarda el producto de 2345 por 7323 en una variable llamada `variablesAreCool`. 20 | 21 | 2. Imprime el resultado en la consola. 22 | -------------------------------------------------------------------------------- /exercises/13-Your_first_switch/tests.js: -------------------------------------------------------------------------------- 1 | const rewire = require('rewire'); 2 | 3 | const file = rewire("./app.js"); 4 | const getColor = file.__get__('getColor'); 5 | test('function getColor should exist', function () { 6 | expect(getColor).toBeTruthy(); 7 | }); 8 | 9 | test(`When calling getColor('red') it should return true`, function () { 10 | expect(getColor('red')).toBe(true); 11 | }); 12 | 13 | test(`When calling getColor('green') it should return true`, function () { 14 | expect(getColor('green')).toBe(true); 15 | }); 16 | 17 | test(`When calling getColor('blue') it should return true`, function () { 18 | expect(getColor('blue')).toBe(true); 19 | }); 20 | 21 | test(`When calling getColor('pink') it should return false`, function () { 22 | expect(getColor('pink')).toBe(false); 23 | }); -------------------------------------------------------------------------------- /exercises/06-String_concatenation/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=qspNmnyqi-U" 3 | --- 4 | 5 | # `06` String Concatenation 6 | 7 | One of JavaScript's strengths is generating HTML code. 8 | 9 | Concatenation comes in handy because you can create and add to existing HTML strings. To concatenate strings, we use the **+** (plus) operator. 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. Set the values for `myVar1`and `myVar2` so the code prints 'Hello World' to the console. 14 | 15 | ## Example: 16 | 17 | ```js 18 | let one = 'a'; 19 | let two = 'b'; 20 | console.log(one+two); //this will print 'ab' on the console. 21 | ``` 22 | 23 | ## 💡 Hint: 24 | 25 | + Here is a 3-minute video explaining how to concatenate strings and ways in which they are useful: https://www.youtube.com/watch?v=cExgK0AnCdM 26 | -------------------------------------------------------------------------------- /exercises/07-Create_a_basic_HTML/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=cIC82hNEZ00" 3 | --- 4 | 5 | # `07` Creating Basic HTML Code 6 | 7 | Continuemos utilizando concatenación de strings para generar HTML. El código de la izquierda contiene 8 constantes con diferentes valores de string. 8 | 9 | ## 📝 Instrucciones: 10 | 11 | 1. Concatena las constantes. 12 | 13 | 2. Establece el valor de la variable `htmlDocument` en un nuevo string que tenga el típico contenido de un documento HTML (con las etiquetas de HTML en el orden correcto). 14 | 15 | 3. Asígnale el valor de la variable `htmlDocument` a este nuevo string e imprime su valor en la consola. 16 | 17 | ## 💡 Pista: 18 | 19 | + El resultado debería verse así: 20 | 21 | ```js 22 | 23 | ``` 24 | -------------------------------------------------------------------------------- /exercises/19-Random_colors_loop/solution.hide.js: -------------------------------------------------------------------------------- 1 | function getColor(colorNumber = 0) { 2 | 3 | //make sure the parameter is a number and not a string by converting the value to int: 4 | colorNumber = parseInt(colorNumber); 5 | switch (colorNumber) { 6 | case 1: return "red"; 7 | 8 | case 2: return "yellow"; 9 | 10 | case 3: return "blue"; 11 | 12 | case 4: return "green"; 13 | 14 | default: return "black"; 15 | 16 | } 17 | } 18 | 19 | function getAllStudentColors() { 20 | 21 | //your loop here 22 | // let exampleColor = getColor(1); 23 | for (let i = 0; i < 10; i++) { 24 | let exampleColor = getColor(Math.floor(Math.random() * 4) + 1) 25 | console.log(exampleColor); 26 | } 27 | } 28 | 29 | //call the function below with the number of students in the class and print on the console 30 | getAllStudentColors(); 31 | 32 | -------------------------------------------------------------------------------- /exercises/06-String_concatenation/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=5wnwecQQLjw" 3 | --- 4 | 5 | # `06` String Concatenation 6 | 7 | Uno de los objetivos principales de JavaScript es generar código HTML. 8 | 9 | La concatenación es útil porque puedes crear y añadir strings a strings de HTML existentes. Para concatenar strings, utilizamos el símbolo **+** (más). 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Establece los valores de `myVar1` y `myVar2` para que el código imprima 'Hello World' en la consola. 14 | 15 | ## Ejemplo: 16 | 17 | ```js 18 | let one = 'a'; 19 | let two = 'b'; 20 | console.log(one+two); //esto imprimirá 'ab' en la consola. 21 | ``` 22 | 23 | ## 💡 Pista: 24 | 25 | + Aquí tienes un video de 3 minutos explicando cómo concatenar strings y para qué son útiles: https://www.youtube.com/watch?v=cExgK0AnCdM 26 | -------------------------------------------------------------------------------- /exercises/23-Bottles_of_milk/solution.hide.js: -------------------------------------------------------------------------------- 1 | function song(){ 2 | for (let i = 99; i >= 0; i--) { 3 | if (i == 1) { 4 | console.log("1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall."); 5 | } else if (i == 0) { 6 | console.log("No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall."); 7 | } else if (i== 2) { 8 | console.log(`${i} bottles of milk on the wall, ${i} bottles of milk. Take one down and pass it around, ${i-1} bottle of milk on the wall.`); 9 | } else { 10 | console.log(`${i} bottles of milk on the wall, ${i} bottles of milk. Take one down and pass it around, ${i-1} bottles of milk on the wall.`); 11 | } 12 | } 13 | } 14 | 15 | song() -------------------------------------------------------------------------------- /exercises/05-Constants/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=prD2J3Ye-uA" 3 | --- 4 | 5 | # `05` Constants 6 | 7 | 8 | Since 2015, JavaScript has allowed the use of **constants**. 9 | 10 | Constants differ from variables because once declared, they cannot have their values changed over time (unlike variables). 11 | 12 | To declare a constant, you have to use the reserved word `const` instead of `var`, like this: 13 | 14 | ```js 15 | const VERSION = '1.2'; 16 | ``` 17 | 18 | Constants are extremely useful. As a developer you may want to make sure parts of your data are read-only. 19 | 20 | ## 📝 Instructions: 21 | 22 | 1. Run the exercise and fix the error that is shown on the console. 23 | 24 | 2. Make the code output `0.9` on the console when fixed. 25 | 26 | ## 💡 Hint: 27 | 28 | + Search for "TypeError assignment to constant variable" on Google.com to learn how to fix it. 29 | -------------------------------------------------------------------------------- /exercises/04-User_inputed_variables/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=NVOYUidj3Es" 3 | --- 4 | 5 | # `04` User Inputted Variables 6 | 7 | Another cool feature about variables is that you don't need to know their value to be able to work with them. 8 | 9 | For example, this application is prompting the user for his or her age. Let's see if we can change it. 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. Please add 10 years to the value of the `age` variable. 14 | 15 | 2. Print the result to the console. 16 | 17 | ## 💡 Hint: 18 | 19 | + The content of a variable is determined by the user's inputs. The `prompt()` function saves the input value as a string. 20 | 21 | + You will have to make sure that the variable is converted to an integer for the calculation to be successfully completed. This is a good opportunity to work on your problem-solving skills by performing a Google search. 22 | -------------------------------------------------------------------------------- /exercises/04-User_inputed_variables/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=2W-f9F0vu7w" 3 | --- 4 | 5 | # `04` User Inputted Variables 6 | 7 | La otra cuestión genial sobre las variables es que no necesitas saber su valor para poder trabajar con ellas. 8 | 9 | Por ejemplo, esta aplicación solicita al usuario su edad. Veamos si podemos cambiarla. 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Por favor añade/suma 10 años al valor de la variable `age`. 14 | 15 | 2. Imprime el resultado en la consola. 16 | 17 | 18 | ## 💡 Pista: 19 | 20 | + El contenido de la variable está determinado por las entradas del usuario. La función `prompt()` guarda el valor ingresado como un string. 21 | 22 | + Debes asegurarte de que la variable esté convertida en un número entero para que el cálculo sea correcto. Esta es una buena oportunidad para trabajar tu capacidad para resolver problemas buscando en Google. 23 | -------------------------------------------------------------------------------- /exercises/12-How_much_the_wedding_costs/README.md: -------------------------------------------------------------------------------- 1 | # `12` How Much Does the Wedding Cost? 2 | 3 | Here is a table of prices of a wedding catering company: 4 | 5 | | Nº of people | Price | 6 | |:---|---:| 7 | | Up to 50 people | $4,000 | 8 | | Up to 100 people | $10,000 | 9 | | Up to 200 people | $15,000 | 10 | | More than 200 people | $20,000 | 11 | 12 | ## 📝 Instructions: 13 | 14 | 1. Write a function `getPrice` that receives the number of guests attending the wedding and returns the corresponding `price` on the console. 15 | 16 | ## 📎 Example: 17 | 18 | For example, if the user says that **20 people** are attending the wedding, the returned price should be **4000**. 19 | 20 | ## 💡 Hints: 21 | 22 | + Use a conditional `if...else` statement to divide your code and assign the variable `price` to the appropriate value. 23 | 24 | + Divide and Conquer: breaking a problem up into smaller pieces that are easier to solve. 25 | -------------------------------------------------------------------------------- /exercises/12-How_much_the_wedding_costs/README.es.md: -------------------------------------------------------------------------------- 1 | # `12` How Much Does the Wedding Cost? 2 | 3 | Aquí está la tabla de precios de una empresa de catering de bodas: 4 | 5 | | Nº de Personas | Precio | 6 | |:---|---:| 7 | | Hasta 50 personas | $4,000 | 8 | | Hasta 100 personas | $10,000 | 9 | | Hasta 200 personas | $15,000 | 10 | | Más de 200 personas | $20,000 | 11 | 12 | ## 📝 Instrucciones: 13 | 14 | 1. Crea una función `getPrice` que reciba la cantidad de personas que van a asistir a la boda y devuelve el precio correspondiente en la consola. 15 | 16 | ## 📎 Ejemplo: 17 | 18 | Por ejemplo, si el usuario dice que **20 personas** van a asistir a la boda, el valor retornado debe ser **4000**. 19 | 20 | ## 💡 Pista: 21 | 22 | + Usa un condicional `if...else` para dividir tu código y establecer el valor de la variable `price` correctamente. 23 | 24 | + Divide y vencerás: divide un problema en partes más pequeñas, más fáciles de resolver. 25 | -------------------------------------------------------------------------------- /exercises/01-Hello_World/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=gMe0ZOHaYQw" 3 | --- 4 | 5 | # `01` Hello World 6 | 7 | In JavaScript, we use `console.log()` to make the computer print anything we want (the content of a variable, a given string, etc.) in something called the `console`. 8 | 9 | Every language has a `console`, as it was the only way to interact with the users at the beginning (before Windows or MacOS arrived). 10 | 11 | Today, printing to the `console` is mainly used as a monitoring tool, ideally to leave a trace of the content of variables during the execution of a program. 12 | 13 | ## 📝 Instructions: 14 | 15 | 1. Use `console.log()` to print `Hello World` on the console. Feel free to try other things as well! 16 | 17 | ## Example: 18 | 19 | ```js 20 | console.log('How are you?'); 21 | ``` 22 | 23 | ## 💡 Hint: 24 | 25 | + Here is a 3 minutes video about [the console](https://www.youtube.com/watch?v=1RlkftxAo-M). 26 | -------------------------------------------------------------------------------- /exercises/04-User_inputed_variables/tests.js: -------------------------------------------------------------------------------- 1 | /* 2 | let age keeps being received as NaN and breaks the test; 3 | tried forcing it to int and then back to string, but none of that helps 4 | */ 5 | 6 | //mock the prompt function 7 | const stdin = ["40"]; 8 | //this mock will pass one by one all the inputs 9 | global.prompt = jest.fn(() => stdin.shift()); 10 | 11 | const rewire = require('rewire'); 12 | const fs = require('fs'); 13 | const path = require('path'); 14 | 15 | const app = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 16 | global.console.log = console.log = jest.fn(text => null); 17 | 18 | it('Declare age variable', function () { 19 | const regex = /let\s+age\s*=\s*prompt\s*\(.*\)/gm 20 | expect(regex.test(app.toString())).toBeTruthy(); 21 | }); 22 | 23 | it('Testing with age = 40, and the console.log() should print 50', function () { 24 | const _ = require('./app'); 25 | expect(console.log).toHaveBeenCalledWith(50); 26 | }); 27 | -------------------------------------------------------------------------------- /.github/workflows/learnpack-audit.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Learnpack audit 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [20.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v2 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | - run: npm install @learnpack/learnpack@latest -g 29 | - run: learnpack audit -------------------------------------------------------------------------------- /exercises/05-Constants/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=7paF5i-9gcQ" 3 | --- 4 | 5 | # `05` Constants 6 | 7 | Desde 2015, JavaScript también permite el uso de **constantes**. 8 | 9 | Se diferencian de las variables porque, una vez declaradas, no se les puede cambiar el valor (a diferencia de las variables). 10 | 11 | Para declarar una constante, debes usar la palabra reservada `const` en vez de `var`, de esta forma: 12 | 13 | ```js 14 | const VERSION = '1.2'; 15 | ``` 16 | 17 | Las constantes son extremadamente útiles porque algunas veces, como programadores, queremos asegurarnos de que ciertos datos sean de solo lectura (read-only). 18 | 19 | ## 📝 Instrucciones: 20 | 21 | 1. Compila el ejercicio y arregla el error que se mostrará en la consola. 22 | 23 | 2. Haz que aparezca `0.9` en la consola cuando esté corregido. 24 | 25 | ## 💡 Pista: 26 | 27 | + Busca "TypeError assignment to constant variable" en Google.com para aprender a corregirlo. 28 | -------------------------------------------------------------------------------- /exercises/22-The_Beatles/README.md: -------------------------------------------------------------------------------- 1 | # `22` The Beatles 2 | 3 | Who doesn't like The Beatles? A BBC study reported that 90% of kids today don't know the band. Heartbreaking... 😟 4 | 5 | Below is the chorus of one of the most famous Beatles songs, *Let It Be*: 6 | 7 | > Let it be, let it be, let it be, let it be 8 | 9 | > Whisper words of wisdom 10 | 11 | > Let it be 12 | 13 | ## 📝 Instructions: 14 | 15 | 1. Create a function called `sing()` that returns a string with the exact same lyrics which you can hear from the 3:20 mark to the end of the song at 3:50. 16 | 17 | ## 💻 Expected output: 18 | 19 | ```js 20 | "let it be, let it be, let it be, let it be, there will be an answer, let it be, let it be, let it be, let it be, let it be, whisper words of wisdom, let it be" 21 | ``` 22 | 23 | ## 💡 Hints: 24 | 25 | + The words `let it be` are repeated in the string. Creating a loop would be a good idea. 26 | 27 | + Here is the song: https://www.youtube.com/watch?v=QDYfEBY9NM4 28 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 2 | 3 | By accessing Breathe Code we assume you accept these terms and conditions. Do not continue to use Breathe Code's content, applications or tutorials if you do not agree to take all of the terms and conditions stated on this page. 4 | 5 | Unless otherwise stated, Breathe Code and/or its licensors own the intellectual property rights for all material on Breathe Code. All intellectual property rights are reserved. You may access this from Breathe Code for your own personal use subjected to restrictions set in these terms and conditions. 6 | 7 | You must not: 8 | 9 | * Republish material from Breathe Code 10 | * Sell, rent or sub-license material from Breathe Code 11 | * Reproduce, duplicate or copy material from Breathe Code 12 | * Redistribute content from Breathe Code 13 | 14 | You can read the full version of Breathe Code's terms and conditions here: [Terms and Conditions](http://breatheco.de/terms-and-conditions) 15 | -------------------------------------------------------------------------------- /exercises/20-Looping_with_FizzBuzz/README.md: -------------------------------------------------------------------------------- 1 | # `20` Looping with FizzBuzz 2 | 3 | This is a typical beginner test that is required to complete interviews in Google, Facebook and all other big tech unicorns. 4 | 5 | ## 📝 Instructions: 6 | 7 | 1. Write the code needed to print to the console all the numbers from `1` to `100`. 8 | 9 | 2. For multiples of 3, instead of the number, print `Fizz`. 10 | 11 | 3. For multiples of 5, print `Buzz`. 12 | 13 | 4. For numbers which are multiples of both 3 and 5, print `FizzBuzz`. 14 | 15 | ## 💻 Expected output: 16 | 17 | ```js 18 | / 19 | 1 20 | 2 21 | Fizz 22 | 4 23 | Buzz 24 | Fizz 25 | 7 26 | 8 27 | Fizz 28 | Buzz 29 | 11 30 | Fizz 31 | 13 32 | 14 33 | FizzBuzz 34 | 16 35 | .... 36 | .... 37 | 98 38 | Fizz 39 | Buzz 40 | / 41 | ``` 42 | 43 | ## 🔎 Important: 44 | 45 | + If you feel stuck and you don't understand loops, go back to these [exercises](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial). 46 | -------------------------------------------------------------------------------- /exercises/01-Hello_World/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=muLPTLOyWCQ" 3 | --- 4 | 5 | # `01` Hello World 6 | 7 | En JavaScript, usamos `console.log` para hacer que el computador imprima cualquier cosa que nosotros queramos (el contenido de una variable, un string, etc.) en algo llamado `la consola`. 8 | 9 | Cada lenguaje tiene una `consola`, ya que era la única forma de interactuar con los usuarios al principio (antes de que Windows o MacOS llegaran). 10 | 11 | Actualmente, imprimir en la `consola` se usa mayormente como una herramienta de monitoreo, ideal para dejar rastros del contenido de variables durante la ejecución del programa. 12 | 13 | ## 📝 Instrucciones: 14 | 15 | 1. Usa `console.log` para imprimir `Hello World` en la consola ¡Siéntete libre de probar otras cosas también! 16 | 17 | 18 | ## Ejemplo: 19 | 20 | ```js 21 | console.log("¿Cómo estás?"); 22 | ``` 23 | 24 | ## 💡 Pista: 25 | 26 | + Aquí hay un Video de 3 minutos sobre [la consola](https://www.youtube.com/watch?v=1RlkftxAo-M). 27 | -------------------------------------------------------------------------------- /exercises/21-Russian_Roulette/README.md: -------------------------------------------------------------------------------- 1 | # `21` Russian Roulette 2 | 3 | Have you ever played Russian Roulette? It's super fun! If you make it (wuuuahahahaha). 4 | 5 | Revolvers can have 6 chambers for bullets. A single bullet is inserted into one of the chambers. The revolver chambers are spun to make the game random. Nobody knows the position of the bullet. FIRE!!!....... Are you dead? 6 | 7 | ## 📝 Instructions: 8 | 9 | The game is almost working. 10 | 11 | 1. The `fireGun()` function needs to be completed to make the game work. It should compare the bullet position against the chamber position. 12 | 13 | ## 💡 Hints: 14 | 15 | + If the bullet position `firePosition` matches the chamber position given by the function `spinChamber`, the function `fireGun()` should return `You're dead!`. 16 | 17 | + If the bullet position `firePosition` doesn't match the chamber position given by the function `spinChamber`, the function `fireGun()` should return `Keep playing!`. 18 | 19 | + The function `spinChamber` returns a random number between 1 and 6. 20 | -------------------------------------------------------------------------------- /exercises/22-The_Beatles/README.es.md: -------------------------------------------------------------------------------- 1 | # `022` The Beatles 2 | 3 | ¿A quién no le gustan Los Beatles? Un estudio de la BBC ha mostrado que el 90% de los niños de ahora no conocen la banda... Qué triste... 😟 4 | 5 | Abajo está el coro de una de las canciones más famosas de Los Beatles, *Let it be*: 6 | 7 | > Let it be, let it be, let it be, let it be 8 | 9 | > Whisper words of wisdom 10 | 11 | > Let it be 12 | 13 | ## 📝 Instrucciones: 14 | 15 | 1. Crea una función llamada `sing()` que devuelva un string con la letra exacta que puedes oír desde el minuto 3:20 hasta el final de la canción a los 3:50 minutos. 16 | 17 | ## 💻 Resultado esperado: 18 | 19 | ```js 20 | "let it be, let it be, let it be, let it be, there will be an answer, let it be, let it be, let it be, let it be, let it be, whisper words of wisdom, let it be" 21 | ``` 22 | 23 | ## 💡 Pistas: 24 | 25 | + Las palabras `let it be` se repiten todo el tiempo, probablemente debas crear un bucle (loop) para eso. 26 | 27 | + Aquí está la canción: https://www.youtube.com/watch?v=QDYfEBY9NM4 28 | -------------------------------------------------------------------------------- /exercises/20-Looping_with_FizzBuzz/README.es.md: -------------------------------------------------------------------------------- 1 | # `20` Looping with FizzBuzz 2 | 3 | Este es un test típico para principiantes que es requerido para completar entrevistas en Google, Facebook y todos los otros grandes unicornios tecnológicos. 4 | 5 | ## 📝 Instrucciones: 6 | 7 | 1. Escribe el código necesario para imprimir en la consola los números del `1` al `100`. 8 | 9 | 2. Para múltiplos de 3, en vez del número, imprime la palabra `Fizz`. 10 | 11 | 3. Para múltiplos de 5, imprime la palabra `Buzz`. 12 | 13 | 4. Para números que sean múltiplos de 3 y 5, imprime `FizzBuzz`. 14 | 15 | ## 💻 Resultado esperado: 16 | 17 | ```js 18 | / 19 | 1 20 | 2 21 | Fizz 22 | 4 23 | Buzz 24 | Fizz 25 | 7 26 | 8 27 | Fizz 28 | Buzz 29 | 11 30 | Fizz 31 | 13 32 | 14 33 | FizzBuzz 34 | 16 35 | .... 36 | .... 37 | 98 38 | Fizz 39 | Buzz 40 | / 41 | ``` 42 | 43 | ## 🔎 Importante: 44 | 45 | + Si sientes que no estás entendiendo los bucles y estás atascado, haz primero estos [ejercicios](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial). 46 | -------------------------------------------------------------------------------- /exercises/21-Russian_Roulette/README.es.md: -------------------------------------------------------------------------------- 1 | # `21` Russian Roulette 2 | 3 | ¿Alguna vez has jugado a la Ruleta Rusa? ¡Es muy divertido! Si logras sobrevivir... (muajajajajaja). 4 | 5 | El revólver sólo tiene 6 récamaras para balas. Tú insertas una bala en uno de las recámaras, y giras las recámaras del revólver para hacer el juego aleatorio. Nadie sabe la posición de la bala ¡¡¡FUEGO!!!....... ¿has muerto? 6 | 7 | ## 📝 Instrucciones: 8 | 9 | El juego casi está funcionando. 10 | 11 | 1. Completa la función `fireGun()` para que el juego funcione. Debes comparar la posición de la bala contra la posición de la recámara. 12 | 13 | ## 💡 Pistas: 14 | 15 | + Si la posición de la bala `firePosition` coincide con la posición de la recámara dada por la función `spinChamber`, la función `fireGun()` debe devolver `You're dead!`. 16 | 17 | + Si la posición de la bala `firePosition` no coincide con la posición de la recámara dada por la función `spinChamber`, la función `fireGun()` debe devolver `Keep playing!`. 18 | 19 | + La función `spinChamber` retorna un número entero aleatorio entre 1 y 6. 20 | -------------------------------------------------------------------------------- /exercises/10-Create_a_new_function/test.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const rewire = require('rewire'); 4 | 5 | test('shortIntroduction function exists', () => { 6 | const file = rewire("./app.js"); 7 | const shortIntroduction = file.__get__('shortIntroduction'); 8 | expect(typeof shortIntroduction).toBe('function'); 9 | }); 10 | 11 | test("shortIntroduction function returns correct introduction", ()=>{ 12 | 13 | const file = rewire("./app.js"); 14 | const shortIntroduction = file.__get__('shortIntroduction'); 15 | 16 | expect(shortIntroduction("Bob", "developer", 25)).toBe("Hello! my name is Bob, my profession is developer. I am 25 years old."); 17 | expect(shortIntroduction("John", "CTO", 43)).toBe("Hello! my name is John, my profession is CTO. I am 43 years old."); 18 | expect(shortIntroduction("Tom", "lead developer", 28)).toBe("Hello! my name is Tom, my profession is lead developer. I am 28 years old."); 19 | expect(shortIntroduction("Alberto", "CIO", 32)).toBe("Hello! my name is Alberto, my profession is CIO. I am 32 years old."); 20 | }); 21 | -------------------------------------------------------------------------------- /exercises/24-Javascript_Objects/app.js: -------------------------------------------------------------------------------- 1 | var person = { 2 | name: "John", //String 3 | lastName: "Doe", 4 | age: 35, //Number 5 | gender: "male", 6 | luckyNumbers: [7, 11, 13, 17], //Array 7 | significantOther: person2 //Object, yes, the same variable/object defined after 8 | }; 9 | 10 | var person2 = { 11 | name: "Jane", 12 | lastName: "Doe", 13 | age: 38, 14 | gender: "female", 15 | luckyNumbers: [2, 4, 6, 8], 16 | significantOther: person 17 | }; 18 | 19 | var family = { 20 | lastName: "Doe", 21 | members: [person, person2] //Array of objects, don't forget to add Jimmy 22 | }; 23 | 24 | 25 | function addAllFamilyLuckyNumbers(anArray){ 26 | let sumOfAllLuckyNumbers = 0; //sumOfAllLuckyNumbers is a number, the sum of all lucky numbers. 27 | 28 | //To-Do: loop and add; consider nested loops 29 | //Hint: use the anArray variable to get all of the lucky numbers 30 | 31 | return sumOfAllLuckyNumbers; 32 | } 33 | 34 | //Enter all your code here: 35 | 36 | 37 | //Do not make changes below: 38 | console.log(addAllFamilyLuckyNumbers(family.members)); 39 | -------------------------------------------------------------------------------- /exercises/17-Create_a_for_loop/README.md: -------------------------------------------------------------------------------- 1 | # `17` Creating a `for` loop 2 | 3 | As we just learned, loops are useful to repeat a task quickly and efficiently using little code. As you continue on your journey as a developer, the `for` loop will become an indispensable tool. 4 | 5 | Here again, is the structure of a `for` loop: 6 | 7 | ```js 8 | for (initialExpression; conditional; incrementalExpression) { 9 | ...statements; 10 | } 11 | ``` 12 | ... and here is an example `for` statement: 13 | 14 | ```js 15 | // a "for" loop 16 | for (let i = 0; i < 10; i++) { 17 | console.log("Hello!") 18 | } 19 | ``` 20 | 21 | Your teacher wants to make sure you understand that asking questions is important in your growth as a programmer. 22 | 23 | ## 📝 Instructions: 24 | 25 | 1. He/She wants you to type `I will write questions if I'm stuck` 300 times to the console! Fortunately, you know a quick way to accomplish this - using a `for` loop! 26 | 27 | 2. Then, create a function called `standardsMaker()` that prints the phrase `I will write questions if I'm stuck` 300 times. 28 | 29 | ## 💡 Hints: 30 | 31 | + Read more on loops here: https://www.w3schools.com/js/js_loop_for.asp 32 | -------------------------------------------------------------------------------- /exercises/14-Random_numbers/README.md: -------------------------------------------------------------------------------- 1 | # `14` Random Numbers 2 | 3 | JavaScript comes with many very useful "pre-defined" functions that you can use. Such as: 4 | 5 | ```js 6 | Math.random(); 7 | ``` 8 | 9 | You can use the `Math.random()` function to get a pseudo-random decimal (also called a **floating-point**, **float**, or **double**) number. This floating-point number will be between 0 and a number `n` (inclusive of 0, but not of n). 10 | 11 | The `Math.random()` function will return a random decimal number between 0 and 1, run the exercise as it is several times to test it. 12 | 13 | ## 📝 Instructions: 14 | 15 | 1. Please update the function code to make it return an integer (no decimals) number between 1 and 10. 16 | 17 | ## 💡 Hints: 18 | 19 | + `Math.random()` only returns decimal numbers from 0 to 1, and we need integer numbers from 1 to 10. 20 | 21 | + Multiply the `Math.random()` function by 10 to move the decimal point one slot to the right. 22 | 23 | + Use the `Math.floor()` function to remove the rest of the decimals and have only integers. 24 | 25 | + You can read how to use these two functions [here](https://www.w3schools.com/jsref/jsref_random.asp). 26 | 27 | -------------------------------------------------------------------------------- /exercises/23-Bottles_of_milk/README.md: -------------------------------------------------------------------------------- 1 | # `23` Bottles of Milk 2 | 3 | Have you heard the song about 99 bottles of milk? It is a great song - not boring at all... 😆 4 | 5 | Here you can hear it: https://www.youtube.com/watch?v=Xy-da43E6Lo 6 | 7 | ## 📝 Instructions: 8 | 9 | 1. Write an algorithm to print the exact same lyrics. You must use a `for` loop. 10 | 11 | ## 💻 Expected output: 12 | 13 | ```js 14 | `99 bottles of milk on the wall, 99 bottles of milk. Take one down and pass it around, 98 bottles of milk on the wall.` 15 | 16 | `98 bottles of milk on the wall, 98 bottles of milk. Take one down and pass it around, 97 bottles of milk on the wall.` 17 | 18 | ... 19 | 20 | `1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall.` 21 | 22 | `No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall.` 23 | ``` 24 | 25 | ## 💡 Hint: 26 | 27 | + The lyrics change slightly when there is one bottle left (singular instead of plural). 28 | 29 | + When there are no more bottles, the last verse changes to `Go to the store and buy some more`. 30 | 31 | 32 | -------------------------------------------------------------------------------- /exercises/17-Create_a_for_loop/README.es.md: -------------------------------------------------------------------------------- 1 | # `17` Creating a `for` loop 2 | 3 | Como ya aprendimos, los bucles son muy útiles para repetir una tarea rápida y eficientemente usando muy pocas líneas de código. Mientras continúas en tu travesía para convertirte en desarrollador, el bucle `for` se convertirá en una herramienta indispensable. 4 | 5 | Esta es la estructura de un bucle `for`: 6 | 7 | ```js 8 | for (expresionInicial; condicional; expresionIncremental) { 9 | ...declaraciones; 10 | } 11 | ``` 12 | 13 | Aquí hay un ejemplo de la declaración `for`: 14 | 15 | ```js 16 | // Un bucle "for" 17 | for (let i = 0; i < 10; i++) { 18 | console.log("Hello!") 19 | } 20 | ``` 21 | 22 | Queremos asegurarnos de que has comprendido que hacer preguntas es importante para tu desarrollo como programador. 23 | 24 | ## 📝 Instrucciones: 25 | 26 | 1. Escribe 300 veces `I will write questions if I'm stuck` ¡Afortunadamente ya conoces una forma rápida de hacerlo! (usando un bucle `for`). 27 | 28 | 2. Crea una función llamada `standardsMaker()` que imprima 300 veces la frase `I will write questions if I'm stuck`. 29 | 30 | ## 💡 Pistas: 31 | 32 | + Lee más acerca de bucles aquí: https://www.w3schools.com/js/js_loop_for.asp 33 | -------------------------------------------------------------------------------- /exercises/14-Random_numbers/README.es.md: -------------------------------------------------------------------------------- 1 | # `14` Random Numbers 2 | 3 | JavaScript viene con un montón de funciones "pre-definidas" muy útiles que puedes utilizar. Una de ellas es: 4 | 5 | ```js 6 | Math.random(); 7 | ``` 8 | 9 | Puedes utilizar la función `Math.random()` para obtener un número decimal (en inglés llamado **floating-point**, **float** o **double**) aleatorio. Este decimal será entre el 0 y un número `n` (incluyendo el 0 pero no el número n). 10 | 11 | La función `Math.random()` devolverá un número decimal aleatorio entre el 0 y 1, compila el ejercicio tal como está varias veces para probarlo. 12 | 13 | ## 📝 Instrucciones: 14 | 15 | 1. Actualiza el código de la función para hacer que devuelva un número entero (no decimales) entre 1 y 10. 16 | 17 | ## 💡 Pistas: 18 | 19 | + `Math.random()` solo devuelve números decimales del 0 al 1, y nosotros necesitamos números enteros del 1 al 10. 20 | 21 | + Multiplica la función `Math.random()` por 10 para mover el decimal un espacio a la derecha. 22 | 23 | + Usa la función `Math.floor()` para eliminar el resto de los decimales y tener solo los enteros. 24 | 25 | + Puedes leer mas sobre como usar estas dos funciones [aquí](https://www.w3schools.com/jsref/jsref_random.asp). 26 | -------------------------------------------------------------------------------- /exercises/16-Your_first_loop/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | describe('All the javascript should match', function () { 16 | beforeEach(() => { 17 | //here I import the HTML into the document 18 | }); 19 | afterEach(() => { jest.resetModules(); }); 20 | 21 | it('console.log() function to be called 101 times once, with argument 100', function () { 22 | 23 | const file = require("./app.js"); 24 | 25 | //Expect the console log to have been called with 100 at least once 26 | expect(console.log).toHaveBeenCalledWith(100); 27 | 28 | //and I expect the console.log to be called 101 times 29 | expect(console.log.mock.calls.length).toBe(101); 30 | }); 31 | 32 | }); 33 | -------------------------------------------------------------------------------- /exercises/23-Bottles_of_milk/README.es.md: -------------------------------------------------------------------------------- 1 | # `23` Bottles of Milk 2 | 3 | ¿Has escuchado la canción sobre 99 botellas de leche (99 bottles of milk)? Es una gran canción - para nada aburrida...😆 4 | 5 | Aquí la puedes escuchar: https://www.youtube.com/watch?v=Xy-da43E6Lo 6 | 7 | ## 📝 Instrucciones: 8 | 9 | 1. Escribe un algoritmo para imprimir la misma letra. Debes usar un `for` loop. 10 | 11 | ## 💻 Resultado esperado: 12 | 13 | ```js 14 | `99 bottles of milk on the wall, 99 bottles of milk. Take one down and pass it around, 98 bottles of milk on the wall.` 15 | 16 | `98 bottles of milk on the wall, 98 bottles of milk. Take one down and pass it around, 97 bottles of milk on the wall.` 17 | 18 | ... 19 | 20 | `1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall.` 21 | 22 | `No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall.` 23 | ``` 24 | 25 | ## 💡 Pistas: 26 | 27 | + Al final de la canción, la letra cambia porque es sólo una botella (singular en vez de plural). 28 | 29 | + Lee la última parte de la letra y verás como la última línea cambia a `Go to the store and buy some more` (anda a comprar más leche). 30 | -------------------------------------------------------------------------------- /exercises/11-Your_first_if/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=kUucFdx6nf0" 3 | --- 4 | 5 | # `11` Your First "If" Statement 6 | 7 | Tu travesía ha alcanzado un momento crucial: **los condicionales**. Los **condicionales** le permiten al usuario navegar a través de un programa en base a sus entradas (inputs). Este es el principio de la lógica computacional. 8 | 9 | La aplicación actual tiene una ventana que pregunta `How many km are left to go?`. 10 | 11 | ## 📝 Instrucciones: 12 | 13 | Una vez que el usuario ingresa la cantidad, tenemos que imprimir una de las siguientes respuestas: 14 | 15 | 1. Si quedan más de 100km, nosotros respondemos: `"We still have a bit of driving left to go"`. 16 | 17 | 2. Si quedan más de 50km, pero menos o igual a 100km nosotros respondemos: `"We'll be there in 5 minutes"`. 18 | 19 | 3. Si quedan menos o igual a 50km, nosotros respondemos: `"I'm parking. I'll see you right now"`. 20 | 21 | ## 💡 Pista: 22 | 23 | + Usa un condicional `If...else` para verificar el valor `total` de la variable. 24 | 25 | + Puedes usar `else if` dentro de tu condicional, si es necesario. 26 | 27 | + Imprime el mensaje correspondiente. 28 | 29 | + Puedes aprender más al respecto [aquí](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else). 30 | -------------------------------------------------------------------------------- /exercises/11-Your_first_if/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=ISVA9y09Kx4&list=PLCVs_S8Skwp9_apbj_ls2euakDALiWqSN&index=12" 3 | --- 4 | 5 | # `11` Your First "If" Statement 6 | 7 | Your journey has now reached a crucial point: **conditional statements**. **Conditionals** allow a user to navigate through a program based upon their inputs. This is the beginning of computer logic. 8 | 9 | The current application has a prompt asking `How many km are left to go?` 10 | 11 | ## 📝 Instructions: 12 | 13 | Once the user inputs an amount, one of the following responses will be printed to the console: 14 | 15 | 1. If there are more than 100 km left to go, we answer: `"We still have a bit of driving left to go"`. 16 | 17 | 2. If there are more than 50 km, but less or equal to 100 km, we answer: `"We'll be there in 5 minutes"`. 18 | 19 | 3. If there are less than or equal to 50 km, we answer: `"I'm parking. I'll see you right now"`. 20 | 21 | ## 💡 Hints: 22 | 23 | + Use an `if...else` statement to check the value of the `total` variable. 24 | 25 | + You can use `else if` within your conditional, if needed. 26 | 27 | + Print the corresponding message to the console. 28 | 29 | + You can learn more about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else). 30 | -------------------------------------------------------------------------------- /exercises/13-Your_first_switch/solution.hide.js: -------------------------------------------------------------------------------- 1 | function getColor(selection) { 2 | switch(selection){ 3 | // Add more options here 4 | case 'red': 5 | return true; 6 | case 'green': 7 | return true; 8 | case 'blue': 9 | return true; 10 | default: 11 | return false; //returns false because the user picked an unavailable color 12 | break; 13 | } 14 | } 15 | 16 | let colorname = prompt('What color do you want?').trim().toLowerCase(); 17 | let isAvailable = getColor(colorname); 18 | 19 | if(isAvailable) 20 | console.log('Good news! That color is available'); 21 | else 22 | console.log('We are sorry, that color is not available'); 23 | 24 | // Another possible solution 25 | /* 26 | function getColor(selection) { 27 | switch(selection){ 28 | // Add more options here 29 | case 'red': case 'green': case 'blue': 30 | return true; 31 | default: 32 | return false; //returns false because the user picked an unavailable color 33 | break; 34 | } 35 | } 36 | 37 | let colorname = prompt('What color do you want?').trim().toLowerCase(); 38 | let isAvailable = getColor(colorname); 39 | 40 | if(isAvailable) 41 | console.log('Good news! That color is available'); 42 | else 43 | console.log('We are sorry, that color is not available'); 44 | 45 | */ 46 | -------------------------------------------------------------------------------- /exercises/08-Calling_your_first_function/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=1S3f_FsWaY8" 3 | --- 4 | 5 | # `08` Calling Your First Function 6 | 7 | **Functions** are an amazing tool for programmers! 8 | 9 | Think of functions like black boxes - you input something, you get something out. 10 | 11 | A function's strengths include, but are not limited to: 12 | 13 | - Encapsulation of code from the rest of the program (hiding code). This is an important concept that you will learn more about as you grow as a developer. 14 | 15 | - Reuse of code in different programs. You can treat functions as tools in a toolbox. This can make coding more efficient and clean. 16 | 17 | - There is an already defined function `isOdd()` that returns `true` if an odd number is passed as an argument, and `false` if the argument is an even number. 18 | 19 | ## 📝 Instructions: 20 | 21 | 1. Call the function `isOdd()` and pass the number 45345 as its argument. 22 | 23 | 2. Print the output of the function to the console. 24 | 25 | ## 🔎 Important: 26 | 27 | + There are exercises dedicated to functions. We encourage you to go and finish those after completing this exercise. Once you feel more comfortable with [functions](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial), return here and continue with these ones. 28 | -------------------------------------------------------------------------------- /exercises/24-Javascript_Objects/tests.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const rewire = require('rewire'); 4 | 5 | jest.dontMock('fs'); 6 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 7 | let _buffer = ""; 8 | let _log = console.log; 9 | 10 | // lets override the console.log function to mock it, 11 | // but we are also going to save what supposed to be the ouput of the console inside _buffer 12 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 13 | 14 | const file = rewire("./app.js"); 15 | const family = file.__get__("family"); 16 | 17 | describe('All the javascript should match', function () { 18 | beforeEach(() => { 19 | //here I import the HTML into the document 20 | }); 21 | afterEach(() => { jest.resetModules(); }); 22 | 23 | it("John Doe's fourth lucky number should be 33" , function(){ 24 | expect(family.members[0].luckyNumbers[3]).toBe(33) 25 | }) 26 | 27 | it('console.log() function should be called with 94 - sum of all family lucky numbers', function () { 28 | const file = require("./app.js"); 29 | expect(_buffer).toBe("94\n"); 30 | //and I expect the console.log to be already called just one time. 31 | expect(console.log.mock.calls.length).toBe(1); 32 | 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /exercises/13-Your_first_switch/README.md: -------------------------------------------------------------------------------- 1 | # `13` Your First Switch Statement 2 | 3 | We can use another form of conditional called a **switch statement**. A switch statement evaluates an expression and matches it to a `case` clause, executing the statements therein. Here is a basic example: 4 | 5 | ```js 6 | const expr = 'One'; 7 | switch (expr) { 8 | case 'One': 9 | console.log('1'); 10 | break; 11 | case 'Zero': 12 | console.log('0'); 13 | break; 14 | default: 15 | console.log('Does not compute.'); 16 | } 17 | ``` 18 | 19 | Imagine that your software is running the inventory of a shoe store. The client needs to know what colors a particular shoe is available in. 20 | 21 | ## 📝 Instructions: 22 | 23 | 1. Complete the `switch` statement with 3 cases for a shoe coming in the following colors: `red`, `green` and `blue`. 24 | 25 | 2. The function needs to return `true` if the user input matches one of the cases listed in the switch statement, `false` otherwise. 26 | 27 | ## 💡 Hints: 28 | 29 | + You may need to convert the user's input to all lowercase lettering to prevent discrepancies. Click the following to help you accomplish this: 30 | 31 | + For all lowercase: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase 32 | 33 | + More on switch statements: http://www.w3schools.com/js/js_switch.asp 34 | -------------------------------------------------------------------------------- /exercises/18-While_loop/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test("Function startCounting should exist", function () { 16 | const file = rewire("./app.js"); 17 | const startCounting = file.__get__('startCounting'); 18 | expect(startCounting).toBeTruthy(); 19 | }); 20 | 21 | 22 | describe('All the javascript should match', function () { 23 | const file = require("./app.js"); 24 | 25 | it('console.log() function to be called 101 times', function () { 26 | 27 | expect(console.log.mock.calls.length).toBe(101); 28 | }); 29 | 30 | it('console.log() function to be called with argument 100', function () { 31 | 32 | expect(console.log).toHaveBeenCalledWith(100); 33 | }); 34 | 35 | 36 | it('console.log() function to be called with argument 0', function () { 37 | 38 | expect(console.log).toHaveBeenCalledWith(0); 39 | }); 40 | 41 | }); 42 | -------------------------------------------------------------------------------- /exercises/18-While_loop/README.md: -------------------------------------------------------------------------------- 1 | # `18` The "while" Loop 2 | 3 | As mentioned in a previous exercise, `while` loops are similar to `for` loops, just structured differently. 4 | 5 | Here it is again: 6 | 7 | ```js 8 | initialExpression; 9 | while (conditional) { 10 | ...statements; 11 | incrementalExpression; 12 | } 13 | ``` 14 | 15 | Now, let's say we write the following `while` loop: 16 | 17 | ```js 18 | let i = 0; 19 | while (i < 10) { 20 | console.log("Goodbye!"); 21 | } 22 | ``` 23 | 24 | You may have experienced this yourself by now. 25 | 26 | Do you notice something is missing? 27 | 28 | We do not have an *incrementalExpression* in our loop. This is a problem because we want to increment the variable `i` until we reach the desired value to exit the loop. If we don't increment `i`, it stays stuck at `0`, leading to an infinite loop. The program has crashed. 29 | 30 | ## 📝 Instructions: 31 | 32 | 1. Fix the `while` loop so that it does not lead to the program crashing via an infinite loop. 33 | 34 | 2. Print the numbers from `100` to `0` to the console. 35 | 36 | 3. Return `counter` once it is `0`. 37 | 38 | ## 🔎 Important: 39 | 40 | + There are exercises dedicated to Arrays. We encourage you to complete those [exercises](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial) after finishing this one. *Once you are more comfortable, return here to continue.* 41 | -------------------------------------------------------------------------------- /exercises/19-Random_colors_loop/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | const app = rewire('./app.js'); 6 | const getAllStudentColors = app.__get__('getAllStudentColors'); 7 | const getColor = app.__get__('getColor'); 8 | jest.dontMock('fs'); 9 | 10 | let _buffer = ""; 11 | let _log = console.log; 12 | 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | describe('All the javascript should match', function () { 16 | 17 | it('function getColor() should exist', function () { 18 | expect(getColor).not.toBe(undefined); 19 | }); 20 | 21 | it('function getAllStudentColors() should exist', function () { 22 | expect(getAllStudentColors).not.toBe(undefined); 23 | }); 24 | 25 | it('console.log() function should be called 10 times', function () { 26 | const file = require("./app.js"); 27 | expect(console.log.mock.calls.length).toBe(10); 28 | 29 | }); 30 | 31 | it('console.log() function should be called with a string', function () { 32 | const file = require("./app.js"); 33 | expect(console.log).toHaveBeenCalledWith(expect.any(String)); 34 | }); 35 | 36 | it('console.log() function should not be called with argument black', function () { 37 | expect(console.log).not.toHaveBeenCalledWith("black"); 38 | }); 39 | }); -------------------------------------------------------------------------------- /exercises/08-Calling_your_first_function/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=M5357xjy2lE" 3 | --- 4 | 5 | # `08` Calling Your First Function 6 | 7 | Las **funciones** son una increíble herramienta por muchas razones. Principalmente porque puedes encapsular tu código en piezas y reutilizar esas piezas muchas veces sin tener que escribir todo el código de nuevo. 8 | 9 | Las fortalezas de las funciones incluyen: 10 | 11 | - Encapsulamiento del código del resto del programa (ocultar código). Este es un concepto importante sobre el cual aprenderás mientras vayas creciendo como desarrollador. 12 | 13 | - Reutilización del código en diferentes programas. Puedes crear funciones como herramientas dentro de una caja de herramientas. Esto hace que la programación sea más eficiente y limpia. 14 | 15 | - La función ya definida `isOdd`, devuelve `true` si un número impar se pasa como parámetro, y `false` si el número es par. 16 | 17 | ## 📝 Instrucciones: 18 | 19 | 1. Por favor llama a la función `isOdd` pasándole el número 45345 como argumento. 20 | 21 | 2. Imprime el resultado de la función en la consola. 22 | 23 | ## 🔎 Importante: 24 | 25 | + Hay una serie de ejercicios dedicados a funciones, te recomendamos que los hagas después de que realices este ejercicio. Cuando te sientas más cómodo con las [funciones](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial) regresa y continúa con estos. 26 | -------------------------------------------------------------------------------- /exercises/13-Your_first_switch/README.es.md: -------------------------------------------------------------------------------- 1 | # `13` Your First Switch Statement 2 | 3 | Podemos usar otra forma de condicional llamada **switch**. Un switch evalúa una expresión y la iguala a la cláusula `case`, ejecutando las declaraciones que hay dentro de ella. Aquí hay un ejemplo básico: 4 | 5 | ```js 6 | const expr = 'Uno'; 7 | switch (expr) { 8 | case 'Uno': 9 | console.log('1'); 10 | break; 11 | case 'Cero': 12 | console.log('0'); 13 | break; 14 | default: 15 | console.log('No computa.'); 16 | } 17 | ``` 18 | 19 | Imagina que tu software está manejando el inventario de una tienda de zapatos. El cliente necesita saber qué colores tienes disponible en un modelo específico de zapatos. 20 | 21 | ## 📝 Instrucciones: 22 | 23 | 1. Completa este condicional `switch` con 3 casos para un zapato disponible en 3 colores: `red`, `green` y `blue`. 24 | 25 | 2. La función debe regresar `true` si el color solicitado es uno de los colores disponibles de arriba o `false` si el color no está disponible. 26 | 27 | ## 💡 Pista: 28 | 29 | + Es posible que debas llevar la entrada (input) del usuario a minúsculas para evitar discrepancias. Haz clic a continuación para que aprendas a hacerlo: 30 | 31 | + Para llevar todo a minúsculas (lowercase): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase 32 | 33 | + Más sobre condicionales switch: http://www.w3schools.com/js/js_switch.asp 34 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | 2 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 3 | // README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node 4 | { 5 | "name": "Node.js", 6 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile 7 | "image": "mcr.microsoft.com/devcontainers/javascript-node:0-16", 8 | "customizations": { 9 | "vscode": { 10 | "settings": { 11 | "editor.defaultFormatter": "esbenp.prettier-vscode", 12 | "workbench.editorAssociations": { 13 | "*.md": "vscode.markdown.preview.editor" 14 | } 15 | }, 16 | "extensions": ["learn-pack.learnpack-vscode"] 17 | } 18 | }, 19 | 20 | // Features to add to the dev container. More info: https://containers.dev/features. 21 | // "features": {}, 22 | 23 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 24 | // "forwardPorts": [], 25 | 26 | "onCreateCommand": "npm i jest@29.7.0 jest-environment-jsdom@29.7.0 -g && npm i @learnpack/learnpack@5.0.13 -g && learnpack plugins:install @learnpack/node@1.1.15" 27 | 28 | // Use 'postCreateCommand' to run commands after the container is created. 29 | // "postCreateCommand": "yarn install", 30 | 31 | // Configure tool-specific properties. 32 | // "customizations": {}, 33 | 34 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. 35 | // "remoteUser": "root" 36 | } 37 | -------------------------------------------------------------------------------- /exercises/21-Russian_Roulette/tests.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const rewire = require('rewire'); 4 | 5 | jest.dontMock('fs'); 6 | let _buffer = ""; 7 | let _log = console.log; 8 | const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 9 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 10 | 11 | 12 | describe('All the javascript should match', function () { 13 | // jest.resetModules(); 14 | 15 | const app = rewire("./app"); 16 | const fireGun = app.__get__("fireGun"); 17 | const firePosition = app.__get__("firePosition"); 18 | 19 | test('The function "fireGun" should exist', () => { 20 | const file = rewire("./app.js"); 21 | const sum = file.__get__("fireGun"); 22 | expect(sum).not.toBe(undefined); 23 | }) 24 | it('Use "if" conditional;', function () { 25 | const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 26 | expect(app_content).toMatch(/if(\s*)\(/); 27 | }); 28 | 29 | it('If fireGun() is false, message should be "Keep playing!"', function () { 30 | for (let i = 1; i <= 6; i++) { 31 | if (i === firePosition) { 32 | expect(fireGun(i)).toContain("You're dead!"); 33 | } 34 | else { 35 | expect(fireGun(i)).toContain("Keep playing!"); 36 | } 37 | } 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /exercises/18-While_loop/README.es.md: -------------------------------------------------------------------------------- 1 | # `18` The "while" Loop 2 | 3 | Como hemos mencionado en un ejercicio anterior, los bucles `while` son similares a los bucles `for`, solo que están estructurados de manera diferente. 4 | 5 | Aquí está nuevamente: 6 | 7 | ```js 8 | expresionInicial; 9 | while (condicional) { 10 | ...declaraciones; 11 | expresionIncremental; 12 | } 13 | ``` 14 | Digamos que tenemos el siguiente bucle `while`: 15 | 16 | ```js 17 | // un bucle "while" 18 | let i = 0; 19 | while (i < 10) { 20 | console.log("Goodbye!"); 21 | } 22 | ``` 23 | 24 | Puede que ya hayas experimentado con este bucle (loop) 25 | 26 | ¿Notas que falta algo? 27 | 28 | No hay una *expresión de incremento* en nuestro bucle. Esto es un problema porque queremos incrementar la variable `i` hasta alcanzar el valor deseado para salirnos del bucle. Si no incrementamos `i`, queda permanentemente en `0`, lo que generará un bucle infinito y hará que nuestro programa deje de funcionar. 29 | 30 | ## 📝 Instrucciones: 31 | 32 | 1. Arregla el bucle `while` para que funcione y no genere un bucle infinito. 33 | 34 | 2. Imprime del 100 al 0. 35 | 36 | 3. Devuelve la variable `counter` cuando llegue a 0. 37 | 38 | ## 🔎 Importante: 39 | 40 | + Hay ejercicios dedicados a Arrays, te recomendamos realizar esos [ejercicios](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial) después de que termines este ejercicio. *Cuando te sientas cómodo con este contenido, regresa y continua con estos ejercicios.* 41 | 42 | -------------------------------------------------------------------------------- /exercises/19-Random_colors_loop/README.md: -------------------------------------------------------------------------------- 1 | # `19` Random Colors Loop 2 | 3 | So far, we have learned about conditionals, random numbers, functions, and looping. Now we are going to tie all of them into one program! Instead of simply returning random numbers, we can return a random selection of whatever we desire. As many times as we want! 4 | 5 | A function called `getColor` has been written that returns a color based on an integer between `1` and `4`, inclusive. For any integer beyond this range, the color `black` will be returned. 6 | 7 | Scenario: You are a teacher in a 10-student classroom. You want to randomly assign **ONE** color (`red`, `yellow`, `blue` or `green`), to **EACH** student. 8 | 9 | (Just ONE color to EACH student) 10 | 11 | ## 📝 Instructions: 12 | 13 | 1. Complete the function `getAllStudentColors()` so that it prints 10 randomly selected colors, one per student. 14 | 15 | ## 💡 Hints: 16 | 17 | + You have 10 students, you need to loop 10 times. 18 | 19 | + Each time you loop, generate a random number between 1-4 using the `Math.floor()` and `Math.random()` built-in functions, which we learned about in previous exercises. 20 | 21 | + Within the loop, you must also call the `getColor()` function to pass the randomly generated number (as an argument) to obtain and return a color. 22 | 23 | + Print the color to the console. 24 | 25 | ## 🔎 Important: 26 | 27 | + If you feel stuck and you don't understand loops, go back to these [exercises](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial). 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /exercises/19-Random_colors_loop/README.es.md: -------------------------------------------------------------------------------- 1 | # `19` Random Colors Loop 2 | 3 | Hasta ahora, hemos aprendido sobre condicionales, números aleatorios, funciones y bucles ¡Ahora vamos a unirlos todos en un programa! En vez de devolver simplemente números aleatorios, podemos devolver una selección aleatoria de lo que queramos ¡Cuántas veces queramos! 4 | 5 | Hemos creado una función llamada `getColor` que regresa un color basado en un número entero entre `1` y `4`(incluido). Cualquier número diferente regresará el color `black`(negro). 6 | 7 | Escenario: Digamos que eres profesor en un aula de 10 estudiantes y quieres asignar de forma aleatoria **UN** color (`red`, `yellow`, `blue` o `green`) a **CADA** estudiante. 8 | 9 | (Solo UN color POR estudiante) 10 | 11 | ## 📝 Instrucciones: 12 | 13 | 1. Completa la función `getAllStudentColors()` para que imprima 10 colores aleatorios, un color por cada estudiante. 14 | 15 | ## 💡 Pistas: 16 | 17 | + Tienes 10 estudiantes, necesitas hacer un bucle 10 veces. 18 | 19 | + Cada vez que hagas un loop, genera un número aleatorio entre 1-4 usando la función `Math.floor()` y `Math.random()` que vimos en los últimos ejercicios. 20 | 21 | + Dentro del bucle, también debes llamar a la función `getColor()` para pasarle los números generados aleatoriamente (como argumento) para obtener y devolver un color. 22 | 23 | + Imprime el color en la consola. 24 | 25 | ## 🔎 Importante: 26 | 27 | + Si sientes que no estás entendiendo los bucles y estás atascado, haz primero estos [ejercicios](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial). 28 | -------------------------------------------------------------------------------- /exercises/24-Javascript_Objects/solution.hide.js: -------------------------------------------------------------------------------- 1 | var person = { 2 | name: "John", //String 3 | lastName: "Doe", 4 | age: 35, //Number 5 | gender: "male", 6 | luckyNumbers: [7, 11, 13, 17], //Array 7 | significantOther: person2 //Object, yes, the same variable/object defined after 8 | }; 9 | 10 | var person2 = { 11 | name: "Jane", 12 | lastName: "Doe", 13 | age: 38, 14 | gender: "female", 15 | luckyNumbers: [2, 4, 6, 8], 16 | significantOther: person 17 | }; 18 | 19 | var person3 = { 20 | name: 'Jimmy', 21 | lastName: 'Doe', 22 | age: 13, 23 | gender: "male", 24 | luckyNumbers: [1, 2, 3, 4], 25 | significantOther: null 26 | } 27 | 28 | var family = { 29 | lastName: "Doe", 30 | members: [person, person2, person3] //Array of objects, don't forget to add Jimmy 31 | }; 32 | 33 | 34 | function addAllFamilyLuckyNumbers(anArray) { 35 | let sumOfAllLuckyNumbers = 0; //sumOfAllLuckyNumbers is a number, the sum of all lucky numbers. 36 | for (let i = 0; i < anArray.length; i++) { 37 | for (let x = 0; x < anArray[i].luckyNumbers.length; x++) { 38 | sumOfAllLuckyNumbers += anArray[i].luckyNumbers[x]; 39 | } 40 | } 41 | //To-Do: loop and add; consider nested loops 42 | //Hint: use the anArray variable to get all of the lucky numbers 43 | 44 | return sumOfAllLuckyNumbers; 45 | } 46 | 47 | //Enter all your code here: 48 | person.luckyNumbers[3] = 33; 49 | 50 | 51 | //Do not make changes below: 52 | console.log(addAllFamilyLuckyNumbers(family.members)); 53 | -------------------------------------------------------------------------------- /exercises/17-Create_a_for_loop/tests.js: -------------------------------------------------------------------------------- 1 | const rewire = require("rewire"); 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | 5 | jest.dontMock('fs'); 6 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 7 | let _buffer = ""; 8 | let _log = console.log; 9 | 10 | // let's override the console.log function to mock it, 11 | // but we are also going to save what is supposed to be the output of the console inside _buffer 12 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 13 | 14 | const file = require("./app.js"); 15 | describe('All the javascript should match', function () { 16 | beforeEach(() => { 17 | //here I import the HTML into the document 18 | }); 19 | 20 | afterEach(() => { jest.resetModules(); }); 21 | 22 | it('Function standardsMaker should exist', function () { 23 | const _app = rewire("./app.js") 24 | const functionExists = _app.__get__('standardsMaker'); 25 | expect(functionExists).toBeTruthy(); 26 | }) 27 | 28 | it('console.log() function to be called 300 times with a string', function () { 29 | expect(console.log.mock.calls.length).toBe(300); 30 | }); 31 | 32 | it('Use a for loop', function () { 33 | const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 34 | expect(app_content).toMatch(/for(\s*)\(/); 35 | }); 36 | 37 | it('The output is not what we expect', function () { 38 | const app = require('./app.js'); 39 | const text = "I will write questions if I'm stuck"; 40 | expect(console.log).toHaveBeenCalledWith(text); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /exercises/01-Hello_World/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | 5 | jest.dontMock('fs'); 6 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 7 | let _buffer = ""; 8 | let _log = console.log; 9 | 10 | // let's override the console.log function to mock it, 11 | // but we are also going to save what is supposed to be the output of the console inside _buffer 12 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 13 | 14 | describe('All the javascript should match', function () { 15 | beforeEach(() => { 16 | //here I import the HTML into the document 17 | }); 18 | afterEach(() => { jest.resetModules(); }); 19 | 20 | it('console.log() function should be called with Hello World', function () { 21 | 22 | /* 23 | Here is how to mock the alert function: 24 | https://stackoverflow.com/questions/41885841/how-to-mock-the-javascript-window-object-using-jest 25 | */ 26 | 27 | //then I import the index.js (which should have the alert() call inside) 28 | const file = require("./app.js"); 29 | 30 | //Expect the console log to have been called with "Hello World" at least one 31 | expect(console.log).toHaveBeenCalledWith("Hello World"); 32 | //and I expect the console.log to be already called just one time. 33 | expect(console.log.mock.calls.length).toBe(1); 34 | 35 | //You can also compare the entire console buffer (if there have been several console.log calls on the exercise) 36 | //expect(_buffer).toBe("Compare with the entire function buffer out"); 37 | }); 38 | }); 39 | -------------------------------------------------------------------------------- /exercises/05-Constants/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test("Variable 'Version' should exist with the value '0.9'", function(){ 16 | const file = rewire("./app.js"); 17 | const VERSION = file.__get__('VERSION'); 18 | expect(VERSION).toBe('0.9'); 19 | }); 20 | 21 | describe('All the javascript should match', function () { 22 | beforeEach(() => { 23 | //here I import the HTML into the document 24 | }); 25 | afterEach(() => { jest.resetModules(); }); 26 | 27 | it('console.log() should display 0.9', function () { 28 | 29 | 30 | //then I import the index.js (which should have the alert() call inside) 31 | const file = require("./app.js"); 32 | 33 | //Expect the console log to have been called with "Hello World" at least one 34 | expect(console.log).toHaveBeenCalledWith("0.9"); 35 | //and I expect the console.log to be already called just one time. 36 | expect(console.log.mock.calls.length).toBe(1); 37 | 38 | //You can also compare the entire console buffer (if there have been several console.log calls on the exercise) 39 | //expect(_buffer).toBe("Compare with the entire function buffer out"); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /exercises/20-Looping_with_FizzBuzz/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | let rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | 14 | let countFizz = 0; 15 | let countBuzz = 0; 16 | let countFizzBuzz = 0; 17 | global.console.log = console.log = jest.fn((text) => { 18 | if (text.toString().toLowerCase() === "fizzbuzz") { countFizzBuzz++ } 19 | else if (text.toString().toLowerCase() === "fizz") { countFizz++ } 20 | else if (text.toString().toLowerCase() === "buzz") { countBuzz++ } 21 | 22 | _buffer += text + "\n"; 23 | 24 | }); 25 | 26 | it('Use a for loop', function () { 27 | const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 28 | expect(app_content).toMatch(/for(\s*)\(/); 29 | }); 30 | 31 | 32 | describe('All the javascript should match', function () { 33 | const file = require("./app.js"); 34 | 35 | it('console.log() function to be called 100 times', function () { 36 | 37 | expect(console.log.mock.calls.length).toBe(100); 38 | }); 39 | 40 | it('FizzBuzz to be called 6 times', function () { 41 | expect(countFizzBuzz).toBe(6); 42 | }); 43 | 44 | it('Buzz to be called 14 times', function () { 45 | expect(countBuzz).toBe(14); 46 | }); 47 | 48 | it('Fizz to be called 27 times', function () { 49 | expect(countFizz).toBe(27); 50 | } 51 | ) 52 | }); 53 | -------------------------------------------------------------------------------- /exercises/02-Print_variables_in_the_console/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test("Variable 'color' should exist with the value 'red'", function(){ 16 | const file = rewire("./app.js"); 17 | const color = file.__get__('color'); 18 | expect(color).toBe("red"); 19 | }); 20 | 21 | describe('All the javascript should match', function () { 22 | beforeEach(() => { 23 | //here I import the HTML into the document 24 | }); 25 | afterEach(() => { jest.resetModules(); }); 26 | 27 | it('console.log() function should be called with variable color', function () { 28 | 29 | //then I import the index.js (which should have the alert() call inside) 30 | const file = require("./app.js"); 31 | const color = 'red'; 32 | 33 | //Expect the console log to have been called with "Hello World" at least one 34 | expect(console.log).toHaveBeenCalledWith(color); 35 | //and I expect the console.log to be already called just one time. 36 | // expect(console.log.mock.calls.length).toBe(2); 37 | 38 | //You can also compare the entire console buffer (if there have been several console.log calls on the exercise) 39 | //expect(_buffer).toBe("Compare with the entire function buffer out"); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /exercises/16-Your_first_loop/README.md: -------------------------------------------------------------------------------- 1 | # `16` Your First Loop 2 | 3 | Loops and iterations allow you to repeat a process quickly and efficiently. The two most commonly used forms are `for` and `while` loops. 4 | 5 | 1. `for` loops look like this: 6 | 7 | ```js 8 | for (initialExpression; conditional; incrementalExpression) { 9 | ...statements; 10 | } 11 | ``` 12 | 13 | Here is an example `for` statement: 14 | 15 | ```js 16 | // a "for" loop 17 | for (let i = 0; i < 10; i++) { 18 | console.log("Hello!") 19 | } 20 | ``` 21 | 22 | 2. `while` loops are similar in nature. They look like this: 23 | 24 | ```js 25 | initialExpression; 26 | while (conditional) { 27 | ...statements; 28 | incrementalExpression; 29 | } 30 | ``` 31 | 32 | And here is an example: 33 | 34 | ```js 35 | // a "while" loop 36 | let i = 0; 37 | while (i < 10) { 38 | console.log("Goodbye!"); 39 | i++; 40 | } 41 | ``` 42 | 43 | As long as the *conditional* is true, the loop will continue to repeat. If the *conditional* is false, the loop will exit. Notice how both types of loops use the same pieces, just organized in a different manner. 44 | 45 | You can use `>` (greater than), `<` (less than), `>=` (greater than or equal to), `<=` (less than or equal to), `===` (equal to), `!==` (not equal to) in your conditionals. 46 | 47 | Running the current code will print the integers `0` through `99` to the console. 48 | 49 | ## 📝 Instructions: 50 | 51 | 1. Change the code to print the integers `0` to `100`. 52 | 53 | ## 🔎 Important: 54 | 55 | + There is a whole series of exercises dedicated to Arrays. We encourage you to complete these [exercises](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial) before finishing this exercise. Once you are more comfortable, return here to continue. 56 | -------------------------------------------------------------------------------- /exercises/10-Create_a_new_function/README.md: -------------------------------------------------------------------------------- 1 | # `10` Creating a New Function 2 | 3 | As you know, functions are a useful block of code that can be reused as many times as you need. In the last exercise, you had a function that received two arguments (two inputs) and returned their sum. 4 | 5 | Something Like this: 6 | 7 | ```js 8 | function addNumbers(a, b){ 9 | return a + b; 10 | } 11 | ``` 12 | 13 | We are going to go ahead and learn some more! Consider this function: 14 | 15 | ```js 16 | function hello(myName) { 17 | console.log("Hello! my name is " + myName) 18 | } 19 | 20 | hello("Jose") // This will print "Hello! my name is Jose" in the console 21 | ``` 22 | 23 | In this block of code we are declaring a function which receives one argument, `myName` which is whatever string (ideally a name) that you choose when calling the function, this will then print in the console the string we declared in the body of the function which is `"Hello! my name is {myName}"` with whatever name we used. 24 | 25 | ## 📝 Instructions: 26 | 27 | 1. Complete the function called `shortIntroduction()`, which returns a short introduction of you. 28 | 29 | 2. The function will ask for 3 arguments: `name`, `profession`, and `age`. 30 | 31 | 3. They should be concatenated as follows: `Hello! my name is {name}, my profession is {profession}. I am {age} years old.` 32 | 33 | 4. Finally, inside a `console.log()`, call the function with the data in the correct order to finish the exercise. 34 | 35 | ## 💡 Hint: 36 | 37 | + Remember to use the plus (+) sign to concatenate different strings and variables in the `console.log()`. Also there are more ways to concatenate strings and variables, if you want to learn more, [click here](https://stackoverflow.com/questions/16600925/how-can-i-add-a-variable-to-console-log). 38 | -------------------------------------------------------------------------------- /exercises/16-Your_first_loop/README.es.md: -------------------------------------------------------------------------------- 1 | # `16` Your First Loop 2 | 3 | Los bucles e iteraciones te permiten repetir un proceso rápida y eficientemente. 4 | 5 | Las dos formas más utilizadas son los bucles `for` y `while`. 6 | 7 | 1. Un bucle `for` se ve así: 8 | 9 | ```js 10 | for (expresionInicial; condicional; expresionIncremental) { 11 | ...declaraciones; 12 | } 13 | ``` 14 | 15 | Aquí hay un ejemplo de la declaración `for`: 16 | 17 | ```js 18 | // Un bucle "for" 19 | for (let i = 0; i < 10; i++) { 20 | console.log("Hello!") 21 | } 22 | ``` 23 | 24 | 2. Los bucles `while` tienen una naturaleza similar. Se ven así: 25 | 26 | ```js 27 | expresionInicial; 28 | while (condicional) { 29 | ...declaraciones; 30 | expresionIncremental; 31 | } 32 | ``` 33 | 34 | Y aquí hay un ejemplo: 35 | 36 | ```js 37 | // un bucle "while" 38 | let i = 0; 39 | while (i < 10) { 40 | console.log("Goodbye!"); 41 | i++; 42 | } 43 | ``` 44 | 45 | Mientras el *condicional* sea true, el bucle continuará repitiéndose. Si el *condicional* es false, el bucle terminará. Fíjate que ambos bucles usan los mismos componentes organizados de manera diferente. 46 | 47 | Puedes usar `>` (mayor que), `<` (menor que), `>=` (mayor que o igual a), `<=` (menor que o igual a), `===` (igual a), `!==` (distinto) en tus condicionales. 48 | 49 | Si compilas este código verás un conteo del `0` al `99` en la consola. 50 | 51 | ## 📝 Instrucciones: 52 | 53 | 1. Arregla el código para que cuente desde el `0` hasta el `100`. 54 | 55 | ## 🔎 Importante: 56 | 57 | + Hay una serie de ejercicios dedicados a Arrays (arreglos). Te recomendamos hacer esos [ejercicios](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial) antes de continuar con este primer ejercicio de Array. Luego, regresa aquí para continuar con estos. 58 | -------------------------------------------------------------------------------- /exercises/09-Creating_your_first_function/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=41QZKUDS9Uw" 3 | --- 4 | 5 | # `09` Creating Your First Function 6 | 7 | To define a function, you have to understand its structure first. For example: 8 | 9 | ```js 10 | function function_name (param1, param2, ...) { 11 | return param1 + param2; 12 | } 13 | ``` 14 | 15 | + Functions begin with the **keyword** `function`. 16 | 17 | + The `function_name` is the name of the function. 18 | 19 | + `(param1, param2, ...)` are the **parameters** (variables) required by the function. They can be integers, strings, decimals, or any combination thereof. You can have zero or more parameters in a given function. Parameters are assigned **arguments**, which are the user's input. 20 | 21 | + The space within the curly brackets `{...}` is the function's body. Here is where the arguments are processed and some sort of output is provided. 22 | 23 | + The output can include returning a value (as shown in the example above), printing to the console, calling another function, etc. 24 | 25 | + The function `addNumbers()` is supposed to return the sum of two given numbers: 26 | 27 | ## 📝 Instructions: 28 | 29 | 1. Complete the necessary code with the function body to make it behave as expected. 30 | 31 | 2. The exercise should print `7` to the console. 32 | 33 | ## 💡 Hint: 34 | 35 | - The function is receiving two arguments (stored in the parameters `a` and `b`). You can create a variable called `sum` within the function body that stores the total of both arguments. 36 | 37 | ## 🔎 Important: 38 | 39 | + There are exercises dedicated to functions. We encourage you to go and finish those after completing this exercise. Once you feel more comfortable with [functions](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial), you should return here. 40 | -------------------------------------------------------------------------------- /exercises/09-Creating_your_first_function/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test("Function addNumbers should exist", function(){ 16 | const file = rewire("./app.js"); 17 | const addNumbers = file.__get__('addNumbers'); 18 | expect(addNumbers).toBeTruthy(); 19 | }); 20 | 21 | describe('All the javascript should match', function () { 22 | beforeEach(() => { 23 | //here I import the HTML into the document 24 | }); 25 | afterEach(() => { jest.resetModules(); }); 26 | 27 | it('console.log() function should be called with the sum of 3 + 4', function () { 28 | 29 | 30 | //then I import the index.js (which should have the alert() call inside) 31 | const file = require("./app.js"); 32 | 33 | //Expect the console log to have been called with the sum of 3 + 4 at least once 34 | expect(console.log).toHaveBeenCalledWith(3+4); 35 | expect(console.log).toHaveBeenCalledWith(2+5); 36 | expect(console.log).toHaveBeenCalledWith(1+6); 37 | //and I expect the console.log to be already called just one time. 38 | expect(console.log.mock.calls.length).toBe(1); 39 | 40 | //You can also compare the entire console buffer (if there have been several console.log calls on the exercise) 41 | //expect(_buffer).toBe("Compare with the entire function buffer out"); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /exercises/08-Calling_your_first_function/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | let rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test("Function isOdd should exist", function(){ 16 | const file = rewire("./app.js"); 17 | const isOdd = file.__get__('isOdd'); 18 | expect(isOdd).toBeTruthy(); 19 | }); 20 | 21 | describe('All the javascript should match', function () { 22 | beforeEach(() => { 23 | //here I import the HTML into the document 24 | }); 25 | afterEach(() => { jest.resetModules(); }); 26 | 27 | it('console.log() function should be called with parameter 45345', function () { 28 | 29 | //then I import the index.js (which should have the alert() call inside) 30 | const file = require("./app.js"); 31 | const _app = rewire('./app'); 32 | const isOdd = _app.__get__("isOdd"); 33 | 34 | expect(console.log).toHaveBeenCalledWith(isOdd(45345)); 35 | //Expect the console log to have been called with parameter 45345 at least once 36 | expect(console.log).toHaveBeenCalledWith(true); 37 | //and I expect the console.log to be already called just one time. 38 | expect(console.log.mock.calls.length).toBe(1); 39 | 40 | //You can also compare the entire console buffer (if there have been several console.log calls on the exercise) 41 | //expect(_buffer).toBe("Compare with the entire function buffer out"); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /exercises/09-Creating_your_first_function/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=t6CPAFQYFuk" 3 | --- 4 | 5 | # `09` Creating Your First Function 6 | 7 | Para definir una función, debes entender cómo se estructura. Por ejemplo: 8 | 9 | ```js 10 | function function_name (param1, param2, ...) { 11 | return param1 + param2; 12 | } 13 | ``` 14 | - Las funciones comienzan con la **palabra reservada** `function`. 15 | 16 | - `function_name` es el nombre de la función. 17 | 18 | - `(param1, param2, ...)` son los **parámetros** (variables) que la función requiere. Pueden ser números enteros, strings o cualquier otra combinación. Puedes tener cero o más parámetros en una función dada. A los parámetros se le asignan **argumentos**, los cuales son las entradas (input) del usuario. 19 | 20 | - El espacio entre llaves `{...}` es el cuerpo (body) de la función. Ahí es donde se procesan los argumentos y provee una especie de resultado. 21 | 22 | - El resultado puede incluir: devolver un valor (como se muestra en el ejemplo anterior), imprimir en la consola, llamar a otra función, etc. 23 | 24 | - La función `addNumbers` se supone que devuelve la suma de 2 números dados. 25 | 26 | ## 📝 Instrucciones: 27 | 28 | 1. Por favor completa el código necesario dentro de la función para que se comporte como se espera. 29 | 30 | 2. El ejercicio debería imprimir `7` en la consola. 31 | 32 | ## 💡 Pista: 33 | 34 | + La función está recibiendo 2 parámetros (variables `a` y `b`). Puedes crear una variable llamada `sum` dentro del cuerpo de la función que guarde el total de ambos argumentos. 35 | 36 | ## 🔎 Importante: 37 | 38 | + Hay una serie de ejercicios dedicados a funciones, te recomendamos que los hagas después de que realices este ejercicio. Cuando te sientas más cómodo con las [funciones](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial) regresa y continúa con estos. 39 | -------------------------------------------------------------------------------- /exercises/10-Create_a_new_function/README.es.md: -------------------------------------------------------------------------------- 1 | --- 2 | tutorial: "https://www.youtube.com/watch?v=8PlacEppf2Y" 3 | --- 4 | 5 | # `10` Creating a New Function 6 | 7 | Como ya sabes, las funciones son un bloque útil de código que puedes reutilizar las veces que desees. En el último ejercicio, tuviste una función que recibía dos argumentos (dos entradas o inputs) y devolvía la suma de ellos. 8 | 9 | De esta forma: 10 | 11 | ```js 12 | function addNumbers(a, b){ 13 | return a + b; 14 | } 15 | ``` 16 | 17 | ¡Así que vamos a seguir aprendiendo más cosas! Analiza la siguiente función: 18 | 19 | ```js 20 | function hello(myName) { 21 | console.log("Hello! my name is " + myName) 22 | } 23 | 24 | hello("Jose") // Esto imprimirá "Hello! my name is Jose" en la consola 25 | ``` 26 | 27 | En este bloque de código estamos declarando una función que recibe un argumento, `myName` que será un string que elijamos (idealmente un nombre) cuando llamemos la función, esto después imprimirá en consola el string que declaramos en el cuerpo de la función siendo `"Hello! my name is {myName}"` con el nombre que hayamos usado. 28 | 29 | ## 📝 Instrucciones: 30 | 31 | 1. Completa la función llamada `shortIntroduction()` la cual retorna una breve presentación sobre ti. 32 | 33 | 2. La función deberá tener 3 argumentos: `name`, `profession` y `age`. 34 | 35 | 3. Estos parámetros se concatenarán de la siguiente manera: `Hello! my name is {name}, my profession is {profession}. I am {age} years old.` 36 | 37 | 4. Finalmente, dentro de un `console.log()`, llama a la función con los datos en el orden correcto para terminar el ejercicio. 38 | 39 | ## 💡 Pista: 40 | 41 | + Recuerda usar el símbolo más (+) para concatenar diferentes strings y variables en el `console.log()`. Además, hay otras formas de concatenar strings y variables, si quieres saber más, [haz clic aquí](https://stackoverflow.com/questions/16600925/how-can-i-add-a-variable-to-console-log). 42 | -------------------------------------------------------------------------------- /exercises/06-String_concatenation/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test("Variable 'myVar1' should exist with the value 'Hello' ", function(){ 16 | const file = rewire("./app.js"); 17 | const myVar1 = file.__get__('myVar1'); 18 | expect(myVar1).toBe("Hello"); 19 | }); 20 | test("Variable 'myVar2' should exist with the value 'World' ", function(){ 21 | const file = rewire("./app.js"); 22 | const myVar2 = file.__get__('myVar2'); 23 | expect(myVar2).toBe("World"); 24 | }); 25 | 26 | describe('All the javascript should match', function () { 27 | beforeEach(() => { 28 | //here I import the HTML into the document 29 | }); 30 | afterEach(() => { jest.resetModules(); }); 31 | 32 | it('console.log() function should display Hello World', function () { 33 | 34 | //then I import the index.js (which should have the alert() call inside) 35 | const file = require("./app.js"); 36 | 37 | //Expect the console log to have been called with "Hello World" at least once 38 | expect(console.log).toHaveBeenCalledWith("Hello World"); 39 | //and I expect the console.log to be already called just one time. 40 | expect(console.log.mock.calls.length).toBe(1); 41 | 42 | //You can also compare the entire console buffer (if there have been several console.log calls on the exercise) 43 | //expect(_buffer).toBe("Compare with the entire function buffer out"); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /exercises/22-The_Beatles/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | it('Use a for loop', function () { 16 | const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 17 | expect(app_content).toMatch(/for(\s*)\(/); 18 | }); 19 | 20 | test("Function sing should exist", function () { 21 | const file = rewire("./app.js"); 22 | const sing = file.__get__('sing'); 23 | expect(sing).toBeTruthy(); 24 | }); 25 | 26 | test("Function sing should return the exact lyrics of the song", function () { 27 | const file = rewire("./app.js"); 28 | const sing = file.__get__('sing'); 29 | expect(sing()).toBe('let it be, let it be, let it be, let it be, there will be an answer, let it be, let it be, let it be, let it be, let it be, whisper words of wisdom, let it be'); 30 | }); 31 | 32 | 33 | describe('All the javascript should match', function () { 34 | beforeEach(() => { 35 | //here I import the HTML into the document 36 | }); 37 | afterEach(() => { jest.resetModules(); }); 38 | 39 | it('console.log() function should be called with proper lyrics order', function () { 40 | 41 | const file = require("./app.js"); 42 | 43 | expect(console.log).toHaveBeenCalledWith("let it be, let it be, let it be, let it be, there will be an answer, let it be, let it be, let it be, let it be, let it be, whisper words of wisdom, let it be"); 44 | 45 | expect(console.log.mock.calls.length).toBe(1); 46 | }); 47 | }); 48 | -------------------------------------------------------------------------------- /exercises/07-Create_a_basic_HTML/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test("Variable 'htmlDocument' should exist", function(){ 16 | const file = rewire("./app.js"); 17 | const htmlDocument = file.__get__('htmlDocument'); 18 | expect(htmlDocument).toBeTruthy(); 19 | }); 20 | 21 | it("'htmlDocument' should have the correct output", function () { 22 | const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 23 | expect(app_content).toMatch(/htmlDocument\s*\W\s*\w\s*\W\s*/); 24 | }); 25 | describe('All the javascript should match', function () { 26 | beforeEach(() => { 27 | //here I import the HTML into the document 28 | }); 29 | afterEach(() => { jest.resetModules(); }); 30 | 31 | it('console.log() function should display ', function () { 32 | const file = require("./app.js"); 33 | 34 | //Expect the console log to have been called with "" at least once 35 | expect(console.log).toHaveBeenCalledWith(""); 36 | //and I expect the console.log to be already called just one time. 37 | expect(console.log.mock.calls.length).toBe(1); 38 | 39 | //You can also compare the entire console buffer (if there have been several console.log calls on the exercise) 40 | //expect(_buffer).toBe("Compare with the entire function buffer out"); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /exercises/12-How_much_the_wedding_costs/tests.js: -------------------------------------------------------------------------------- 1 | 2 | let rewire = require('rewire'); 3 | let fs = require('fs'); 4 | let path = require('path'); 5 | 6 | it("Create an if statement", function () { 7 | const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 8 | expect(app_content).toMatch(/if\s*/); 9 | }); 10 | 11 | it('The function getPrice must exist', function () { 12 | 13 | const app = rewire('./app.js'); 14 | const getPrice = app.__get__('getPrice') 15 | expect(getPrice).toBeTruthy(); 16 | }); 17 | 18 | it('When tested for 50 it should return 4000', function () { 19 | 20 | const app = rewire('./app.js'); 21 | const getPrice = app.__get__('getPrice') 22 | expect(getPrice(50)).toBe(4000); 23 | }); 24 | 25 | it('When tested for 51 it should return 10000', function () { 26 | 27 | const app = rewire('./app.js'); 28 | const getPrice = app.__get__('getPrice') 29 | expect(getPrice(51)).toBe(10000); 30 | }); 31 | it('When tested for 100 it should return 10000', function () { 32 | 33 | const app = rewire('./app.js'); 34 | const getPrice = app.__get__('getPrice') 35 | expect(getPrice(100)).toBe(10000); 36 | }); 37 | it('When tested for 101 it should return 15000', function () { 38 | 39 | const app = rewire('./app.js'); 40 | const getPrice = app.__get__('getPrice') 41 | expect(getPrice(101)).toBe(15000); 42 | }); 43 | it('When tested for 200 it should return 15000', function () { 44 | 45 | const app = rewire('./app.js'); 46 | const getPrice = app.__get__('getPrice') 47 | expect(getPrice(200)).toBe(15000); 48 | }); 49 | it('When tested for 201 it should return 20000', function () { 50 | const app = rewire('./app.js'); 51 | const getPrice = app.__get__('getPrice') 52 | expect(getPrice(201)).toBe(20000); 53 | }); 54 | it('When tested for 400 it should return 20000', function () { 55 | const app = rewire('./app.js'); 56 | const getPrice = app.__get__('getPrice') 57 | expect(getPrice(400)).toBe(20000); 58 | }); 59 | -------------------------------------------------------------------------------- /exercises/03-Multiply_two_values/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test("The variable 'variablesAreCool' should exist", function(){ 16 | const file = rewire("./app.js"); 17 | const variablesAreCool = file.__get__('variablesAreCool'); 18 | expect(variablesAreCool).toBeTruthy(); 19 | }); 20 | 21 | test("The variable 'variablesAreCool' should store the value of '2345 * 7323'", function(){ 22 | const file = rewire("./app.js"); 23 | const variablesAreCool = file.__get__('variablesAreCool'); 24 | expect(variablesAreCool).toBe(2345*7323); 25 | }); 26 | 27 | describe('All the javascript should match', function () { 28 | beforeEach(() => { 29 | //here I import the HTML into the document 30 | }); 31 | afterEach(() => { jest.resetModules(); }); 32 | 33 | it('console.log() function should be called with variablesAreCool', function () { 34 | 35 | //then I import the index.js (which should have the alert() call inside) 36 | const file = require("./app.js"); 37 | const variablesAreCool = 2345 * 7323; 38 | 39 | //Expect the console log to have been called with "Hello World" at least one 40 | expect(console.log).toHaveBeenCalledWith(variablesAreCool); 41 | //and I expect the console.log to be already called just one time. 42 | expect(console.log.mock.calls.length).toBe(1); 43 | 44 | //You can also compare the entire console buffer (if there have been several console.log calls on the exercise) 45 | //expect(_buffer).toBe("Compare with the entire function buffer out"); 46 | }); 47 | }); 48 | -------------------------------------------------------------------------------- /learn.json: -------------------------------------------------------------------------------- 1 | { 2 | "slug": "javascript-beginner-exercises-tutorial", 3 | "grading": "isolated", 4 | "repository": "https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial", 5 | "title": { 6 | "us": "Javascript Beginner Tutorial (interactive)", 7 | "es": "Tutorial para Principiantes de Javascript (Interactivo)" 8 | }, 9 | "preview": "https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/master/preview.png?raw=true", 10 | "description": { 11 | "us": "Enhance your Javascript programming skills with this comprehensive set of interactive and auto-graded exercises. These exercises cover fundamental topics such as variables, loops, conditionals, functions, and arrays. By completing these exercises, students will gain a solid understanding of Javascript basics, preparing them for more advanced programming challenges. Technologies and topics included are ES6 syntax and basic algorithmic thinking.", 12 | "es": "Mejora tus habilidades de programación en Javascript con este conjunto completo de ejercicios interactivos y auto-evaluados. Estos ejercicios cubren temas fundamentales como variables, bucles, condicionales, funciones y arreglos. Al completar estos ejercicios, los estudiantes obtendrán una comprensión sólida de los conceptos básicos de Javascript, preparándolos para desafíos de programación más avanzados. Las tecnologías y temas incluidos son sintaxis ES6 y pensamiento algorítmico básico." 13 | }, 14 | "duration": 8, 15 | "difficulty": "easy", 16 | "videoSolutions": true, 17 | "bugsLink": "https://github.com/learnpack/learnpack/issues", 18 | "graded": true, 19 | "editor": { 20 | "version": "5.0", 21 | "agent": "vscode" 22 | }, 23 | "telemetry": { 24 | "batch": "https://breathecode.herokuapp.com/v1/assignment/me/telemetry?asset_id=149" 25 | }, 26 | "video": { 27 | "intro": { 28 | "es": "https://www.youtube.com/watch?v=32WbSowUcjc", 29 | "en": "https://www.youtube.com/watch?v=GjQEotj3t6Y" 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /exercises/14-Random_numbers/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | 16 | test('function getRandomInt should exist', function () { 17 | 18 | //then I import the index.js (which should have the alert() call inside) 19 | const file = rewire("./app.js"); 20 | const getRandomInt = file.__get__('getRandomInt'); 21 | 22 | //Expect the console log to have been called with a random 0-9 number at least once 23 | expect(getRandomInt).toBeTruthy(); 24 | 25 | }); 26 | 27 | test('getRandomInt should return something', function () { 28 | 29 | //then I import the index.js (which should have the alert() call inside) 30 | const file = rewire("./app.js"); 31 | const getRandomInt = file.__get__('getRandomInt'); 32 | 33 | //Expect the console log to have been called with a random 0-9 number at least once 34 | expect(getRandomInt()).toBeTruthy(); 35 | 36 | }); 37 | 38 | test('getRandomInt should return an integer (no decimals)', function () { 39 | 40 | //then I import the index.js (which should have the alert() call inside) 41 | const file = rewire("./app.js"); 42 | const getRandomInt = file.__get__('getRandomInt'); 43 | const _int = getRandomInt(); 44 | expect(Math.floor(_int)).toBe(_int); 45 | }); 46 | 47 | test('getRandomInt should return random between 1,10', function () { 48 | 49 | //then I import the index.js (which should have the alert() call inside) 50 | const file = rewire("./app.js"); 51 | const getRandomInt = file.__get__('getRandomInt'); 52 | 53 | //Expect the console log to have been called with a random 0-9 number at least once 54 | for(let i = 0; i < 50; i++) { 55 | const _int = getRandomInt(); 56 | expect(_int).toBeGreaterThanOrEqual(1); 57 | expect(_int).toBeLessThanOrEqual(10); 58 | } 59 | }); 60 | -------------------------------------------------------------------------------- /exercises/15-Rand_from_one_to_six/tests.js: -------------------------------------------------------------------------------- 1 | 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | const rewire = require('rewire'); 5 | 6 | jest.dontMock('fs'); 7 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 8 | let _buffer = ""; 9 | let _log = console.log; 10 | 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | 15 | test('function getRandomInt should exist', function () { 16 | 17 | //then I import the index.js (which should have the alert() call inside) 18 | const file = rewire("./app.js"); 19 | const getRandomInt = file.__get__('getRandomInt'); 20 | 21 | //Expect the console log to have been called with a random 0-9 number at least once 22 | expect(getRandomInt).toBeTruthy(); 23 | 24 | }); 25 | 26 | test('getRandomInt should return something', function () { 27 | 28 | //then I import the index.js (which should have the alert() call inside) 29 | const file = rewire("./app.js"); 30 | const getRandomInt = file.__get__('getRandomInt'); 31 | 32 | //Expect the console log to have been called with a random 0-9 number at least once 33 | expect(getRandomInt()).toBeTruthy(); 34 | 35 | }); 36 | 37 | test('getRandomInt should return an integer (no decimals)', function () { 38 | 39 | //then I import the index.js (which should have the alert() call inside) 40 | const file = rewire("./app.js"); 41 | const getRandomInt = file.__get__('getRandomInt'); 42 | const _int = getRandomInt(); 43 | expect(Math.floor(_int)).toBe(_int); 44 | }); 45 | 46 | test('getRandomInt should return random between 1 and 6', function () { 47 | 48 | //then I import the index.js (which should have the alert() call inside) 49 | const file = rewire("./app.js"); 50 | const getRandomInt = file.__get__('getRandomInt'); 51 | 52 | //Expect the console log to have been called with a random 0-9 number at least once 53 | for(let i = 0; i < 50; i++) { 54 | const _int = getRandomInt(); 55 | expect(_int).toBeGreaterThanOrEqual(1); 56 | expect(_int).toBeLessThanOrEqual(6); 57 | } 58 | }); 59 | -------------------------------------------------------------------------------- /exercises/23-Bottles_of_milk/tests.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const js = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 4 | 5 | jest.dontMock('fs'); 6 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 7 | let _buffer = ""; 8 | let _log = console.log; 9 | 10 | // let's override the console.log function to mock it, 11 | // but we are also going to save what is supposed to be the output of the console inside _buffer 12 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 13 | 14 | describe('All the javascript should match', function () { 15 | it('console.log() function should be called 99 or 100 times (depending on your approach)', function () { 16 | const file = require("./app.js"); 17 | expect([100,99].includes(console.log.mock.calls.length)).toBeTruthy(); 18 | }); 19 | 20 | it('Use a for loop', function () { 21 | const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); 22 | expect(app_content).toMatch(/for(\s*)\(/); 23 | }); 24 | 25 | it('console.log() function should be called with proper lyrics for more than one bottle', function () { 26 | const file = require("./app.js"); 27 | for(let i = 99; i > 2; i--){ 28 | expect(_buffer).toContain(`${i} bottles of milk on the wall, ${i} bottles of milk. Take one down and pass it around, ${i-1} bottles of milk on the wall.`); 29 | } 30 | }); 31 | 32 | it('console.log() function should be called with proper lyrics for two bottles', function () { 33 | const file = require("./app.js"); 34 | expect(_buffer).toContain("2 bottles of milk on the wall, 2 bottles of milk. Take one down and pass it around, 1 bottle of milk on the wall."); 35 | }); 36 | 37 | it('console.log() function should be called with proper lyrics for one bottle', function () { 38 | const file = require("./app.js"); 39 | expect(_buffer).toContain("1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall."); 40 | }); 41 | 42 | it('console.log() function should be called with proper lyrics for 0 bottles', function () { 43 | const file = require("./app.js"); 44 | expect(_buffer).toContain("No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall."); 45 | }); 46 | 47 | it('You should use a for loop to print the lyrics of the song', function () { 48 | const file = require("./app.js"); 49 | let regex = /for\s*\(/gm 50 | expect(regex.test(js.toString())).toBeTruthy(); 51 | }); 52 | }); 53 | -------------------------------------------------------------------------------- /exercises/24-Javascript_Objects/README.md: -------------------------------------------------------------------------------- 1 | # `24` JavaScript Objects 2 | 3 | Often you'll find yourself wanting to save more information in less space, especially if it's all related. 4 | 5 | For example, let's say that we want to represent cars into variables: 6 | 7 | ```js 8 | let car1Model = "Corolla"; 9 | let car1Make = "Toyota"; 10 | let car1Color = "green"; 11 | let car1Year = 2015; 12 | 13 | let car2Model = "Santa Fe"; 14 | let car2Make = "Hyundai"; 15 | let car2Color = "purple"; 16 | let car2Year = 2013; 17 | 18 | //... (you get the idea) 19 | ``` 20 | 21 | There's an optimized approach to this, it is called **Objects**. **Objects** are a type of variable that contains information (other variables) in a **key:value** manner. 22 | 23 | So if we want to translate (and optimize) the variables from the car into an Object, we do: 24 | 25 | ```js 26 | const car1 = {model: "Corolla", make: "Toyota", color: "green", year: 2015}; 27 | ``` 28 | 29 | You can see the `key:value` separated by a comma. And for us (developers) to read it easier we write it like this: 30 | 31 | ```js 32 | const car1 = { 33 | model: "Corolla", 34 | make: "Toyota", 35 | color: "green", 36 | year: 2015 37 | }; 38 | ``` 39 | 40 | Looks like a function, right? But it's not. 41 | 42 | Now we are storing information in a more organized way, and if we want to get that information we can do: 43 | 44 | ```js 45 | console.log(car1.model); //prints the model of car1 in the console 46 | ``` 47 | 48 | We can have all of the known types of variables defined as the value of any `key` (including objects!). Now imagine the possibilities... 49 | 50 | ```js 51 | var person = { 52 | name: "John", //String 53 | lastName: "Doe", 54 | age: 35, //Number 55 | gender: "male", 56 | luckyNumbers: [7, 11, 13, 17], //Array 57 | significantOther: person2 //Object, yes, the same variable/object defined after 58 | }; 59 | 60 | var person2 = { 61 | name: "Jane", 62 | lastName: "Doe", 63 | age: 38, 64 | gender: "female", 65 | luckyNumbers: [2, 4, 6, 8], 66 | significantOther: person 67 | }; 68 | 69 | var family = { 70 | lastName: "Doe", 71 | members: [person, person2] //Array of objects 72 | }; 73 | ``` 74 | 75 | So, in this scenario if we want to know the name of the first member of the Doe family we do: 76 | 77 | ```js 78 | console.log(family.members[0].name); 79 | ``` 80 | 81 | Or the 3rd lucky number of the `significantOther` of the second member of the Doe family: 82 | 83 | ```js 84 | console.log(family.members[1].significantOther.luckyNumbers[2]); 85 | ``` 86 | 87 | Easy stuff :) 88 | 89 | ## 📝 Instructions: 90 | 91 | 1. Programmatically, change the fourth `luckyNumber` of John Doe to `33` (use a command, don't manually change the code). 92 | 93 | 2. Programmatically, create a new person and add it to the family object. `Jimmy Doe`, `13`, `male`, `luckyNumbers`: `1`, `2`, `3`, `4`; `significantOther: null`. 94 | 95 | 3. Now please print (`console.log()`) the SUM of all the `luckyNumbers` of the Doe family. 96 | 97 | ## 💡 Hint: 98 | 99 | + You can get each array of `luckyNumbers` from each person object inside the family object. 100 | 101 | + Once you get each array, just loop over it adding every element (like we've been doing so far). And then add each sum of the 3 family members. 102 | 103 | + `null` is also an object. 104 | -------------------------------------------------------------------------------- /exercises/24-Javascript_Objects/README.es.md: -------------------------------------------------------------------------------- 1 | # `24` JavaScript Objects 2 | 3 | A menudo te encontrarás queriendo guardar más información en menos espacio, especialmente si está toda relacionada. 4 | 5 | Por ejemplo, digamos que queremos representar autos dentro de variables: 6 | 7 | ```js 8 | let car1Model = "Corolla"; 9 | let car1Make = "Toyota"; 10 | let car1Color = "green"; 11 | let car1Year = 2015; 12 | 13 | let car2Model = "Santa Fe"; 14 | let car2Make = "Hyundai"; 15 | let car2Color = "purple"; 16 | let car2Year = 2013; 17 | 18 | //... (¿entiendes la idea?) 19 | ``` 20 | 21 | 22 | Hay un enfoque óptimo para esto, son los **objetos**. Los **objetos (objects)** son un tipo de variable que contienen información (otras variables) en forma de `key:value`. 23 | 24 | Entonces, si queremos traducir (y optimizar) las variables desde car (auto) a un Object, hacemos: 25 | 26 | ```js 27 | const car1 = {model: "Corolla", make: "Toyota", color: "green", year: 2015}; 28 | ``` 29 | 30 | Puedes ver el `key:value` separado por una coma. 31 | 32 | Y para que nosotros (los desarrolladores) podamos leerlas más fácilmente las escribimos así: 33 | 34 | ```js 35 | const car1 = { 36 | model: "Corolla", 37 | make: "Toyota", 38 | color: "green", 39 | year: 2015 40 | }; 41 | ``` 42 | 43 | Parece una función, ¿verdad? Pero no lo es. 44 | 45 | Ahora estamos guardando información de una forma más organizada, y si queremos obtener esa información podemos hacer: 46 | 47 | ```js 48 | console.log(car1.model); //imprime el modelo de car1 en la consola 49 | ``` 50 | 51 | Podemos tener todos los tipos de variables conocidas en JavaScript como valor(`value`) de cualquier `key` (¡incluyendo objetos!). Ahora imagina las posibilidades... 52 | 53 | ```js 54 | var person = { 55 | name: "John", //String 56 | lastName: "Doe", 57 | age: 35, //Número 58 | gender: "male", 59 | luckyNumbers: [7, 11, 13, 17], //Array 60 | significantOther: person2 //Objeto, sí, la misma variable/objeto definida después 61 | }; 62 | 63 | var person2 = { 64 | name: "Jane", 65 | lastName: "Doe", 66 | age: 38, 67 | gender: "female", 68 | luckyNumbers: [2, 4, 6, 8], 69 | significantOther: person 70 | }; 71 | 72 | var family = { 73 | lastName: "Doe", 74 | members: [person, person2] //Array de objetos 75 | }; 76 | ``` 77 | 78 | Entonces, si en este escenario queremos saber el nombre del primer miembro de la familia Doe, decimos: 79 | 80 | ```js 81 | console.log(family.members[0].name); 82 | ``` 83 | 84 | O el 3er número de la suerte del `significantOther` del segundo miembro de la familia Doe: 85 | 86 | ```js 87 | console.log(family.members[1].significantOther.luckyNumbers[2]); 88 | ``` 89 | 90 | Cosas sencillas :) 91 | 92 | ## 📝 Instrucciones: 93 | 94 | 1. De forma automatizada, cambia el cuarto número de la suerte de John Doe (`luckyNumber`) a `33` (usa un comando, no cambies manualmente el código). 95 | 96 | 2. De forma automatizada, crea una nueva persona y añádela al objeto familia. `Jimmy Doe`, `13`, `male`(masculino), `luckyNumbers` (números de la suerte): `1`, `2`, `3`, `4`; `significantOther: null`. 97 | 98 | 3. Ahora por favor imprime (`console.log()`) la SUMA de todos los números de la suerte (`luckyNumbers`) de la familia Doe. 99 | 100 | ## 💡 Pistas: 101 | 102 | + Puedes obtener cada array de números de la suerte (`luckyNumbers`) desde el objeto de cada persona dentro del objeto familia. 103 | 104 | + Una vez obtengas cada array, solo has un loop sobre él sumando cada elemento (como hemos hecho hasta ahora). Luego obtén el total de la suma de los 3 miembros de la familia. 105 | 106 | + `null` también es un objeto. 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScript exercises tutorial at 4Geeks Academy 2 | 3 | 4 | 5 | 6 | > By [@alesanchezr](https://twitter.com/alesanchezr) and [other contributors](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/graphs/contributors) at [4Geeks Academy](https://4geeksacademy.co/) 7 | 8 | ![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-beginner-exercises-tutorial) 9 | [![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) 10 | [![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) 11 | 12 | *Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/master/README.es.md) :es:* 13 | 14 | 15 | Complete selection of auto-graded and interactive JavaScript exercises for anyone interested in learning JavaScript! 16 | 17 | 18 | ## Before you start... some related tutorials: 19 |
    20 |
  1. JavaScript for Beginners ← 🔥 You are here
  2. 21 |
  3. Looping with JavaScript
  4. 22 |
  5. JavaScript Functions
  6. 23 |
  7. Master JavaScript
  8. 24 |
25 | 26 | > We need you! These exercises are built and maintained in collaboration with contributors such as yourself. If you find any bugs or misspellings please contribute and/or report them. 27 | 28 | ## One click installation (recommended): 29 | 30 | You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-beginner-exercises-tutorial) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial.git). 31 | 32 | > Once you have VSCode open the LearnPack exercises should start automatically. If exercises don't run automatically you can try typing on your terminal: `$ learnpack start` 33 | 34 | ## Local Installation 35 | 36 | [Clone the repository](https://4geeks.com/how-to/github-clone-repository) in your local environment and follow the steps below: 37 | 38 | 1. Install LearnPack, the package manager for learning tutorials and the node compiler plugin for learnpack, make sure you also have node.js 16+: 39 | 40 | ```bash 41 | $ npm i @learnpack/learnpack -g 42 | ``` 43 | 44 | 2. Start the tutorial/exercises by running the following command at the same level where your learn.json file is: 45 | 46 | ```bash 47 | $ learnpack start 48 | ``` 49 | 50 | 51 | > Note: The exercises have automatic grading, but it's very rigid and strict, my recommendation is to not take the tests too serious and use them only as a suggestion, or you may get frustrated. 52 | 53 | ## How are the exercises organized? 54 | 55 | Each exercise is a small React application containing the following files: 56 | 57 | 1. **app.js:** represents the entry JavaScript file that will be executed by the computer. 58 | 2. **README.md:** contains exercise instructions. 59 | 3. **test.js:** contains the testing script for the exercise (you don't have to open this file). 60 | 61 | ## Contributors 62 | 63 | Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 64 | 65 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 👀 (build-tutorial) ✅ (documentation) 📖 66 | 67 | 2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, contribution: (coder), (translation) 🌎 68 | 69 | 3. [Ricardo Rodriguez (RickRodriguez8080)](https://github.com/RickRodriguez8080) contribution: (build-tutorial) ✅, (documentation) 📖 70 | 71 | This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! 72 | 73 | This and many other exercises are built by students as part of the 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) by [Alejandro Sánchez](https://twitter.com/alesanchezr) and many other contributors. Find out more about our [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer), and [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning). 74 | -------------------------------------------------------------------------------- /README.es.md: -------------------------------------------------------------------------------- 1 | # Tutorial de ejercicios de JavaScript para Principiantes en 4Geeks Academy 2 | 3 | 4 | 5 | 6 | > Por [@alesanchezr](https://twitter.com/alesanchezr) y [otros colaboradores](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/graphs/contributors) de [4Geeks Academy](https://4geeksacademy.co/) 7 | 8 | ![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-beginner-exercises-tutorial) 9 | [![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) 10 | [![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) 11 | 12 | 13 | ¡Selección completa de ejercicios de JavaScript interactivos autograduados para cualquier persona interesada en aprender JavaScript! 14 | 15 | 16 | ## Antes de empezar... algunos tutoriales relacionados 17 |
    18 |
  1. JavaScript para Principiantes ← 🔥 Estás aquí
  2. 19 |
  3. Looping con JavaScript
  4. 20 |
  5. Funciones de JavaScript
  6. 21 |
  7. Master JavaScript
  8. 22 |
23 | 24 | > ¡Te necesitamos! Estos ejercicios se crean y mantienen con colaboradores como tú. Si encuentras algún error o falta de ortografía, contribuye y/o infórmanos. 25 | 26 | ## Instalación en un clic (recomendado) 27 | 28 | Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-beginner-exercises-tutorial) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial.git). 29 | 30 | > Una vez ya tengas abierto VSCode, los ejercicios de LearnPack deberían empezar automáticamente; si esto no sucede puedes intentar empezar los ejercicios escribiendo este comando en tu terminal: `$ learnpack start` 31 | 32 | ## Instalación local: 33 | 34 | Clona el repositorio en tu ambiente local y sigue los siguientes pasos: 35 | 36 | 1. Instala LearnPack, el package manager para los tutoriales interactivos y el node compiler plugin para LearnPack, asegúrate también de tener node.js 14: 37 | 38 | ```bash 39 | $ npm i @learnpack/learnpack -g 40 | ``` 41 | 42 | 2. Inicializa el tutorial/ejercicios ejecutando el siguiente comando en el mismo nivel donde se encuentra su archivo learn.json: 43 | 44 | ```bash 45 | $ learnpack start 46 | ``` 47 | 48 | 49 | 50 | > Nota: Estos ejercicios tienen calificación automática. Los tests son muy rígidos y estrictos, mi recomendación es que no prestes demasiada atención a los tests y los uses solo como una sugerencia o podrías frustrarte. 51 | 52 | ## ¿Cómo están organizados los ejercicios? 53 | 54 | Cada ejercicio es una pequeña aplicación de React que contiene los siguientes archivos: 55 | 56 | 1. **app.js:** representa el archivo JavaScript de entrada que ejecutará la computadora. 57 | 2. **README.md:** contiene las instrucciones de ejercicio. 58 | 3. **test.js:** contiene el script del test para el ejercicio (no es necesario que abras este archivo). 59 | 60 | ## Colaboradores 61 | 62 | Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 63 | 64 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 🤓 (build-tutorial) ✅ (documentación) 📖 65 | 66 | 2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador), (traducción) 🌎 67 | 68 | 3. [Ricardo Rodriguez (RickRodriguez8080)](https://github.com/RickRodriguez8080) contribución: (build-tutorial) ✅, (documentación) 📖 69 | 70 | Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! 71 | 72 | Este y otros ejercicios son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por parte de los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) realizado por [Alejandro Sánchez](https://twitter.com/alesanchezr) y muchos otros contribuyentes. Conoce más sobre nuestro [Curso de Programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero?lang=es) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack/?lang=es), o nuestro [Data Science Bootcamp](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). 73 | -------------------------------------------------------------------------------- /exercises/11-Your_first_if/tests.js: -------------------------------------------------------------------------------- 1 | describe('All tests', () => { 2 | afterEach(() => { 3 | jest.resetModules(); 4 | }); 5 | 6 | describe('Testing with 50', () => { 7 | beforeEach(() => { 8 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 9 | let _buffer = ""; 10 | let _log = console.log; 11 | // let's override the console.log function to mock it, 12 | // but we are also going to save what is supposed to be the output of the console inside _buffer 13 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 14 | const stdin = ["50"] 15 | global.prompt = jest.fn(() => stdin.shift()); 16 | const file = require("./app.js"); 17 | 18 | }) 19 | it("If there are less than or equal to 50 km (50), we answer: I'm parking. I'll see you right now", function () { 20 | expect(console.log).toHaveBeenCalledWith("I'm parking. I'll see you right now"); 21 | 22 | }); 23 | 24 | it('Your algorithm should use console.log at least one time, if you believe you are using it make sure it\'s not being conditionally ignored', function () { 25 | expect(console.log.mock.calls.length > 0).toBe(true); 26 | }); 27 | }) 28 | 29 | describe('Testing with 49', () => { 30 | beforeEach(() => { 31 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 32 | let _buffer = ""; 33 | let _log = console.log; 34 | // let's override the console.log function to mock it, 35 | // but we are also going to save what is supposed to be the output of the console inside _buffer 36 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 37 | const stdin = ["49"] 38 | global.prompt = jest.fn(() => stdin.shift()); 39 | const file = require("./app.js"); 40 | }) 41 | it("If there are less than or equal to 50 km (49), we answer: I'm parking. I'll see you right now", function () { 42 | 43 | expect(console.log).toHaveBeenCalledWith("I'm parking. I'll see you right now"); 44 | }); 45 | }) 46 | 47 | describe('Testing with 99', () => { 48 | beforeEach(() => { 49 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 50 | let _buffer = ""; 51 | let _log = console.log; 52 | // let's override the console.log function to mock it, 53 | // but we are also going to save what is supposed to be the output of the console inside _buffer 54 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 55 | const stdin = ["99"] 56 | global.prompt = jest.fn(() => stdin.shift()); 57 | const file = require("./app.js"); 58 | }) 59 | it("If there are more than 50 km, but less or equal to 100 km (99), we answer: We'll be there in 5 minutes", function () { 60 | 61 | expect(console.log).toHaveBeenCalledWith("We'll be there in 5 minutes"); 62 | }); 63 | }) 64 | describe('Testing with 100', () => { 65 | beforeEach(() => { 66 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 67 | let _buffer = ""; 68 | let _log = console.log; 69 | // let's override the console.log function to mock it, 70 | // but we are also going to save what is supposed to be the output of the console inside _buffer 71 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 72 | const stdin = ["100"] 73 | global.prompt = jest.fn(() => stdin.shift()); 74 | const file = require("./app.js"); 75 | }) 76 | it("If there are 100 km left to go, we answer: We'll be there in 5 minutes", function () { 77 | 78 | expect(console.log).toHaveBeenCalledWith("We'll be there in 5 minutes"); 79 | }); 80 | }) 81 | describe('Testing with 101', () => { 82 | beforeEach(() => { 83 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 84 | let _buffer = ""; 85 | let _log = console.log; 86 | // let's override the console.log function to mock it, 87 | // but we are also going to save what is supposed to be the output of the console inside _buffer 88 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 89 | const stdin = ["101"] 90 | global.prompt = jest.fn(() => stdin.shift()); 91 | const file = require("./app.js"); 92 | }) 93 | it('If there are more than 100 km left to go, we answer: We still have a bit of driving left to go', function () { 94 | 95 | expect(console.log).toHaveBeenCalledWith("We still have a bit of driving left to go"); 96 | }); 97 | }) 98 | describe('Testing with 200', () => { 99 | beforeEach(() => { 100 | //here we are going to store and accumulate (concatenate) all the console log's from the exercise 101 | let _buffer = ""; 102 | let _log = console.log; 103 | // let's override the console.log function to mock it, 104 | // but we are also going to save what is supposed to be the output of the console inside _buffer 105 | global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); 106 | const stdin = ["200"] 107 | global.prompt = jest.fn(() => stdin.shift()); 108 | const file = require("./app.js"); 109 | }) 110 | it('If there are more than 100 km left to go, we answer: We still have a bit of driving left to go', function () { 111 | 112 | expect(console.log).toHaveBeenCalledWith("We still have a bit of driving left to go"); 113 | }); 114 | }) 115 | 116 | 117 | 118 | 119 | }) 120 | 121 | 122 | --------------------------------------------------------------------------------