From 90a4542df67cc6a547b9c18b66f6a714787276ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20L=C3=B3pez?= <145539062+KrilinZ@users.noreply.github.com> Date: Mon, 3 Aug 2026 14:10:51 +0200 Subject: [PATCH 1/4] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.md | 211 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 155 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 6623caf..8db4647 100644 --- a/README.md +++ b/README.md @@ -1,94 +1,193 @@ -# Practice Functions in JavaScript +
- +# Practice Javascript Functions Tutorial -> By [@alesanchezr](https://twitter.com/alesanchezr) and [other contributors](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial/graphs/contributors) at [4Geeks Academy](https://4geeksacademy.co/) +Tutorial cover: the words Learn How to use FUNCTIONS next to the yellow JavaScript logo and a hand icon clicking a button -![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-arrays-exercises-tutorial) -[![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) -[![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) +[![Certified tutorial](https://img.shields.io/badge/4Geeks_Academy-Certified_tutorial-2563eb)](https://4geeks.com/en/interactive-exercise/javascript-functions-exercises-tutorial) +[![Autograded with LearnPack](https://img.shields.io/badge/LearnPack-10_autograded_exercises-2563eb)](https://github.com/learnpack/learnpack) +[![Open in GitHub Codespaces](https://img.shields.io/badge/Open_in-GitHub_Codespaces-fb5a1f)](https://codespaces.new/?repo=4GeeksAcademy/javascript-functions-exercises-tutorial) -## Before you start... some related tutorials: -
    -
  1. JavaScript for Beginners
  2. -
  3. Looping with JavaScript
  4. -
  5. JavaScript Functions ← 🔥 You are here
  6. -
  7. Master JavaScript
  8. -
+Read these instructions in [🇪🇸 Spanish](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial/blob/HEAD/README.es.md) -*Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial/blob/master/README.es.md) :es:* +
-Learn the basics about functions in JavaScript: +This LearnPack tutorial has 11 exercise folders about JavaScript functions: one welcome screen plus 10 challenges graded automatically by Jest on Node.js 22. You practice declaring and calling functions, parameters, the `return` statement, anonymous function expressions, arrow functions and `.sort()`. It is rated easy, takes around 5 hours, and every exercise comes with instructions in both English and Spanish. -1. Basic theory about functions in JavaScript. -2. Learn the syntax on how to create functions. -3. How to call functions. -4. What are function parameters and the return statement. -5. How to create traditional, arrow and anonymous functions. -6. Use functions in different scenarios, like for replacing vowels in a string. + +## 📋 About this tutorial + +- **Difficulty:** easy, for people who already write variables and `if` statements but have never written a function. +- **Estimated duration:** 5 hours. +- **Technologies:** JavaScript, Node.js. +- **Exercises:** 11 folders, 10 of them with an automated test file. +- **Grading:** automatic, Jest 29.7.0 plus `rewire` to read the variables inside your file. +- **Video solutions:** all 10 graded exercises link a walkthrough video in Spanish, 4 of them also in English. +- **Languages:** every exercise ships with `README.md` and `README.es.md`. + -These exercises are intended to be built by collaboration, we need you! If you find any bugs or misspells please contribute and report them. +## 🎯 What will you learn? - +The tutorial covers the core of JavaScript functions, one idea per exercise: -## One click installation (recommended): +- **What a function actually is:** a fragment of code wrapped in curly brackets that you write once and reuse as many times as you want. +- **Declaring versus calling:** a function does nothing until something calls it, and the interpreter only knows it exists once it has been defined. +- **Parameters and arguments:** how many to declare, why descriptive names matter, and how the values travel into the function body. +- **The `return` statement:** why almost every function should return something, and how returning lets you feed one function's result straight into another one. +- **Scope:** what lives inside the curly brackets stays local, what lives outside is global. +- **Anonymous functions:** functions with no name that only work when you store them in a variable, such as `let multi = function(a, b) { ... }`. +- **Arrow functions:** the `=>` syntax, why it exists, and how it removes the need for `.bind()` when you later move on to React. +- **Built-in array methods:** using `.sort()` inside your own function to return a list of names in alphabetical order. +- **Printing to the console:** `console.log()` as a tracing tool to inspect what a function is returning. -You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-functions-exercises-tutorial) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial). +## 👀 What will you build? -> Once you have VSCode open, if exercises don't run automatically you can try typing on your terminal: `$ learnpack start` +Each exercise is a small Node.js program that you complete inside `app.js`. These are the 10 graded ones: -## Local Installation +- **`01` Hello World:** call `console.log()` exactly once so the console prints `Hello World`. +- **`02` What is a Function:** the `sum()` function is already written for you; call it with `3445324` and `53454423` and store the result, `56899747`, in a variable named `superduper`. +- **`03` Calling a Function:** call the ready-made `calculateArea()` three times, once per figure, and store the results in `squareArea1`, `squareArea2` and `squareArea3`. +- **`04` Defining VS Calling a Function:** write `multi` from scratch so it takes two numbers and returns their multiplication. It is graded with `multi(3, 6)` and `multi(4, 12)`, and the file already calls it with `multi(7, 53812212)`. +- **`05` Anonymous Functions:** `multi` is now an anonymous function stored in a variable. Use it to print the multiplication of `324234` by `47`, which is `15238998`. +- **`06` Arrow Function:** `multi` arrives here as a traditional `function` declaration; rewrite it with the arrow syntax. The output must stay identical, but the keyword `function` has to disappear from the file. +- **`07` Functions Should Return:** you get `dollarToEuro()` and `euroToYen()`. Chain them to convert 137 dollars into yen and print the result, `15137.609500000002`. +- **`08` Function Parameters:** write `renderPerson()` with five parameters so that it returns the sentence `Bob is a 23 years old male born in 05/22/1983 with green eyes`. +- **`09` Array Methods:** write `sortNames()` so that it receives an array of names, sorts it with `.sort()` and returns the sorted array. +- **`10` Remove Vowels:** write an arrow function called `rapid` that loops a string, drops every vowel and uppercases the rest, so `rapid("Wonderful")` returns `WNDRFL`. -Clone the repository in your local environment and follow the steps below: +These are the three figures of exercise `03`, and the reason `calculateArea()` has to be called with `(4, 4)`, `(2, 2)` and `(5, 5)`: -1. Install LearnPack, the package manager for learning tutorials and the node compiler plugin for LearnPack, make sure you also have node.js 14+: +![Three squares drawn side by side with their dimensions written on the sides: a first square of 4 by 4 inches, a smaller one of 2 by 2 inches and a bigger one of 5 by 5 inches](https://raw.githubusercontent.com/4GeeksAcademy/javascript-functions-exercises-tutorial/master/.learn/assets/call-a-function.png) -```bash -$ npm i learnpack -g -$ learnpack plugins:install learnpack-node -``` +## 🎓 What do you need before starting? -2. Download this particular exercise using LearnPack and `cd` into the folder: +- **Basic JavaScript syntax:** declaring variables with `let` or `const`, and reading a simple `if`. Exercise `01` starts at `console.log()`, so nothing else is assumed. +- **No previous experience with functions:** the definition, the syntax, the parameters and the `return` are all taught from zero inside the tutorial. +- **No local setup if you use Codespaces:** the dev container already installs Node.js 22, Jest and the LearnPack CLI for you. +- **Node.js if you run it locally:** every exercise runs on Node, there is no browser, HTML or DOM involved. -```bash -$ learnpack download javascript-functions-exercises-tutorial -$ cd javascript-functions-exercises-tutorial -``` +## ✅ How does the automatic grading work? + +10 of the 11 folders contain a test file: nine are called `tests.js` and the one in `07-Function-that-returns` is called `test.js`. Only `00-Welcome`, the intro screen, has none. When you click `Run`, LearnPack executes that file with Jest 29.7.0 and shows you exactly which assertion failed. + +The tests check three different things, and knowing which one broke saves a lot of guessing: + +1. **What you printed.** `console.log` is replaced by a mock, so the tests can count how many times you called it and compare the exact value it received. + +2. **Your variables and functions by name.** The test loads `app.js` with `rewire` and pulls values out of it, so names like `superduper`, `squareArea1`, `multi`, `renderPerson`, `sortNames` or `rapid` must match the exercise literally. + +3. **The source code of your `app.js`.** Several tests read the file as plain text and run a regular expression over it. That is how exercise `09` demands `.sort(` and exercise `10` demands both `const rapid = ... =>` and a `for` loop. + +> 💡 The grading is deliberately strict, but treat it as a guide and not as a judge. If an exercise blocks you, open the menu, move on and come back later. + +## 💡 What mistakes should you avoid? + +1. **Printing when the exercise expects a `return`.** In `04`, `08`, `09` and `10` the `console.log()` line is already written at the bottom of `app.js`. If your function ends with a print instead of `return`, it returns `undefined` and the assertions fail even though the console looks fine. + +2. **Writing the word `function` in exercise `06`.** The test runs the regex `/function/gm` over the whole file and fails if it matches anywhere, comments included. It also checks that `multi.prototype` is `undefined`, so only a real arrow function passes. + +3. **Declaring `rapid` with `let` in exercise `10`.** The regex expects `const rapid = ... =>`, and a second test requires a `for` loop, so solving it with `replace()` and no loop fails too. + +4. **Not using the exact numbers in the source.** Exercises `02`, `03` and `05` grep your file for the literal calls: `sum(3445324, 53454423)`, `calculateArea(4, 4)`, `calculateArea(2, 2)`, `calculateArea(5, 5)` and `multi(324234, 47)`. Precomputing the result and assigning it by hand does not pass. + +5. **Leaving extra `console.log()` calls behind.** Exercises `01`, `05`, `06`, `07` and `08` assert that the console was called exactly once. A leftover debugging print turns a correct solution red. + +6. **Returning a string where a number is expected.** Exercises `05` and `06` compare against the number `15238998`, so wrapping it in a template literal or concatenating any text makes the comparison fail. + +7. **Changing the sentence or the parameter order in `08`.** The call already in the file is `renderPerson('Bob', '05/22/1983', 'green', 23, 'male')`, so the order is name, birth date, eye colour, age and gender. The expected string is compared character by character, including the words `is a`, `years old`, `born in` and `with green eyes`. + +## ❓ Frequently asked questions + +### Do I need to install anything to start? + +No. Opening the repository in GitHub Codespaces gives you a container that installs Node.js 22, Jest 29.7.0 and the LearnPack CLI on its own, and the exercises open inside VS Code by themselves. Installing locally is optional and only requires Node.js plus a couple of commands in the terminal. -> Note: Once you finish downloading, you will find an "exercises" folder that contains all the exercises within. +### How long does it take to finish the 10 exercises? -3. Start the tutorial/exercises by running the following command at the same level where your learn.json file is: +The package is estimated at 5 hours. The first ones are two-minute drills around `console.log()` and calling an existing function; the last three (`08` Function Parameters, `09` Array Methods and `10` Remove Vowels) are small algorithms where most of the time goes. + +### What is the difference between a regular function, an anonymous function and an arrow function? + +A regular function has a name of its own: `function multi(a, b) { return a * b; }`. An anonymous function has none, so it only becomes usable once you store it in a variable: `let multi = function(a, b) { return a * b; }`. An arrow function is a shorter form of the second one, `const multi = (a, b) => a * b`, and it does not create its own `this`, which is why it needs no `.bind()`. Exercises `04`, `05` and `06` walk the same multiplication through all three styles: you write it yourself in `04`, you get it ready-made as an anonymous function in `05`, and you turn it into an arrow in `06`. + +### Why does my exercise fail if the console output looks correct? + +Because several tests do not look at the console at all. Some read your source code with a regular expression, others load your variables with `rewire` and call your function with values you never tried, such as `multi(4, 12)` in exercise `04` or `rapid("Wonderful")` in exercise `10`. Read the name of the failing assertion: it tells you which of the three checks broke. + +### Are the exercises and the video solutions available in Spanish? + +Yes. All 11 folders include `README.md` and `README.es.md`, and you can switch language from the exercise menu without losing progress. The Spanish version links a walkthrough video for all 10 graded exercises; the English version links 4 of them, on exercises `01`, `02`, `04` and `05`. + +### Does it cost anything, and who owns the code I write? + +Access to this repository and its exercises costs nothing, and whatever you write inside `app.js` is yours. The tutorial content itself is not open source: it is published under reserved intellectual property terms that do not allow republishing or redistributing it. The full text is in [LICENSE.md](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial/blob/HEAD/LICENSE.md). + + +## 📚 Related tutorials + +This package is the third step of the interactive JavaScript series: + +1. [JavaScript for Beginners](https://4geeks.com/en/interactive-exercise/javascript-beginner-exercises) +2. [Arrays and Loops](https://4geeks.com/en/interactive-exercise/javascript-array-loops-exercises) +3. **JavaScript Functions** ← you are here +4. [Master JavaScript Practicing](https://4geeks.com/en/interactive-exercise/master-javascript-exercises) + +## 🚀 How to start + +The fastest way is [Open in GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-functions-exercises-tutorial). The container installs everything and the exercises start on their own inside VS Code. + +If they do not start automatically, run this in the terminal: ```bash -$ npm i jest@24.8.0 -g -$ learnpack start +learnpack start ``` - +You can also open the package in [Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial). Use the top menu to move between exercises and to switch the instructions between English and Spanish. + +## 💻 Local installation + +Clone the repository and follow these steps: +1. Install LearnPack and its Node.js compiler plugin. You need Node.js installed first: -## How are the exercises organized? + ```bash + npm i @learnpack/learnpack -g + learnpack plugins:install @learnpack/node + ``` -Each exercise is a small React application containing the following files: +2. Start the tutorial from the same folder where `learn.json` lives: -1. **app.js:** represents the entry file for the exercise. -2. **README.md:** contains exercise instructions. -3. **test.js:** you don't have to open this file, it contains the testing script for the exercise. + ```bash + learnpack start + ``` -> 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. +If something goes wrong, the [LearnPack quickstart for learners](https://4geeks.com/docs/learnpack/quickstart-for-learners) walks through the whole setup. -## Contributors +## 📝 How the exercises are organized -Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +Each of the 10 graded folders inside `exercises/` is one small Node.js program with these files: -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 👀 (build-tutorial) ✅ (documentation) 📖 +- **`app.js`:** the file you edit, and the entry point that gets executed. +- **`README.md`:** the instructions in English. +- **`README.es.md`:** the same instructions in Spanish. +- **`tests.js`:** the Jest test that grades your solution, named `test.js` in exercise `07`. You do not need to open it. +- **`solution.hide.js`:** a working solution, hidden by LearnPack until you ask for it. -2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, contribution: (coder), (translation) 🌎 +`00-Welcome` is the exception: it is only the intro screen and contains nothing but the two `README` files. -3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) :🐛, (translation) 🌎 +## 🤝 Contributors -This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! +Thanks to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): -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). +1. [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr): coder 💻, idea 🤔, build-tests ⚠️, pull-request-review 👀, build-tutorial ✅, documentation 📖 + +2. [Paolo (plucodev)](https://github.com/plucodev): bug reports 🐛, coder 💻, translation 🌎 + +3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo): bug reports 🐛, translation 🌎 + +4. [Luis Rivera (Luis846)](https://github.com/Luis846): coder 💻, build-tests ⚠️ + +See the full list on the [contributors graph](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial/graphs/contributors). This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification and contributions of any kind are welcome. If you find a bug or a typo, please report it or send a pull request. + From ccdce92978c0f25fcb72578d4c18f182c461b640 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20L=C3=B3pez?= <145539062+KrilinZ@users.noreply.github.com> Date: Mon, 3 Aug 2026 14:10:53 +0200 Subject: [PATCH 2/4] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.es.md | 211 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 156 insertions(+), 55 deletions(-) diff --git a/README.es.md b/README.es.md index 1a22811..f60d0ce 100644 --- a/README.es.md +++ b/README.es.md @@ -1,92 +1,193 @@ +
-# Practica Funciones en JavaScript +# Tutorial para Practicar Funciones de Javascript - +Portada del tutorial: las palabras Learn How to use FUNCTIONS junto al logo amarillo de JavaScript y el icono de una mano pulsando un botón -> Por [@alesanchezr](https://twitter.com/alesanchezr) y [otros colaboradores](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/graphs/contributors) at [4Geeks Academy](https://4geeksacademy.co/) +[![Tutorial certificado](https://img.shields.io/badge/4Geeks_Academy-Tutorial_certificado-2563eb)](https://4geeks.com/es/interactive-exercise/javascript-functions-exercises-tutorial-es) +[![Autocorregido con LearnPack](https://img.shields.io/badge/LearnPack-10_ejercicios_autocorregidos-2563eb)](https://github.com/learnpack/learnpack) +[![Abrir en GitHub Codespaces](https://img.shields.io/badge/Abrir_en-GitHub_Codespaces-fb5a1f)](https://codespaces.new/?repo=4GeeksAcademy/javascript-functions-exercises-tutorial) -![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-arrays-exercises-tutorial) -[![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) -[![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) +Lee estas instrucciones en [🇺🇸 inglés](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial/blob/HEAD/README.md) -#### Antes de empezar... Algunos tutoriales relacionados -
    -
  1. JavaScript para Principiantes
  2. -
  3. Looping con JavaScript
  4. -
  5. Funciones de JavaScript ← 🔥 Estás aquí
  6. -
  7. Master JavaScripts
  8. -
+
+ + +Este tutorial de LearnPack tiene 11 carpetas de ejercicios sobre funciones en JavaScript: una pantalla de bienvenida y 10 retos que se corrigen solos con Jest sobre Node.js 22. Practicarás declarar y llamar funciones, los parámetros, la instrucción `return`, las funciones anónimas, las funciones flecha y `.sort()`. Su dificultad es fácil, dura unas 5 horas y cada ejercicio viene con instrucciones en español y en inglés. + +## 📋 Sobre este tutorial + +- **Dificultad:** fácil, pensado para quien ya escribe variables y algún `if` pero nunca ha escrito una función. +- **Duración estimada:** 5 horas. +- **Tecnologías:** JavaScript, Node.js. +- **Ejercicios:** 11 carpetas, 10 de ellas con fichero de test automático. +- **Corrección:** automática, con Jest 29.7.0 y `rewire` para leer las variables de tu fichero. +- **Videosoluciones:** los 10 ejercicios corregidos enlazan un vídeo explicativo en español; 4 lo tienen también en inglés. +- **Idiomas:** cada ejercicio incluye `README.md` y `README.es.md`. -Siendo JavaScript un lenguaje "funcional" es de entender porque las funciones son tan importantes de aprender. En este tutorial aprenderás lo básico que necesitas para manejarte con funciones: +## 🎯 ¿Qué vas a aprender? -1. Teoría básica de funciones en JavaScript. -2. Aprende la sintaxis para crear funciones. -3. Cómo llamar funciones. -4. Qué son los parámetros de una función y la instrucción return. -5. Funciones tradicionales, funciones flecha (arrow) y funciones anónimas. -6. Usa funciones en casos prácticos. +El tutorial recorre lo esencial de las funciones en JavaScript, una idea por ejercicio: -¡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. +- **Qué es realmente una función:** un trozo de código encerrado entre llaves que escribes una vez y reutilizas tantas veces como quieras. +- **Declarar no es llamar:** una función no hace nada hasta que alguien la invoca, y el intérprete solo sabe que existe cuando ya ha sido definida. +- **Parámetros y argumentos:** cuántos declarar, por qué conviene ponerles nombres descriptivos y cómo entran los valores en el cuerpo de la función. +- **La instrucción `return`:** por qué casi toda función debería devolver algo y cómo eso te permite encadenar el resultado de una función dentro de otra. +- **El scope:** lo que vive dentro de las llaves es local, lo que vive fuera es global. +- **Funciones anónimas:** funciones sin nombre que solo puedes usar si las guardas en una variable, del tipo `let multi = function(a, b) { ... }`. +- **Funciones flecha:** la sintaxis `=>`, por qué existe y cómo evita tener que usar `.bind()` cuando más adelante llegues a React. +- **Métodos propios de los arrays:** usar `.sort()` dentro de tu propia función para devolver una lista de nombres en orden alfabético. +- **Imprimir en la consola:** `console.log()` como herramienta para ir viendo qué devuelve una función. - +## 👀 ¿Qué vas a construir? -## Instalación en un clic (recomendado) +Cada ejercicio es un pequeño programa de Node.js que completas dentro de `app.js`. Estos son los 10 que se corrigen: -Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-functions-exercises) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-functions-exercises). +- **`01` Hello World:** llamar a `console.log()` una sola vez para que la consola imprima `Hello World`. +- **`02` What is a Function:** la función `sum()` ya está escrita; llámala con `3445324` y `53454423` y guarda el resultado, `56899747`, en una variable llamada `superduper`. +- **`03` Calling a Function:** llamar tres veces a la función `calculateArea()`, ya escrita, una por cada figura, y guardar los resultados en `squareArea1`, `squareArea2` y `squareArea3`. +- **`04` Defining VS Calling a Function:** escribir `multi` desde cero para que reciba dos números y devuelva su multiplicación. Se corrige con `multi(3, 6)` y `multi(4, 12)`, y el fichero ya la llama con `multi(7, 53812212)`. +- **`05` Anonymous Functions:** aquí `multi` es una función anónima guardada en una variable. Úsala para imprimir la multiplicación de `324234` por `47`, que da `15238998`. +- **`06` Arrow Function:** aquí `multi` llega como declaración `function` tradicional; hay que reescribirla con sintaxis de flecha. La salida debe ser idéntica, pero la palabra `function` tiene que desaparecer del fichero. +- **`07` Functions Should Return:** te dan `dollarToEuro()` y `euroToYen()`. Encadénalas para convertir 137 dólares a yenes e imprimir el resultado, `15137.609500000002`. +- **`08` Function Parameters:** escribir `renderPerson()` con cinco parámetros para que devuelva la frase `Bob is a 23 years old male born in 05/22/1983 with green eyes`. +- **`09` Array Methods:** escribir `sortNames()` para que reciba un array de nombres, lo ordene con `.sort()` y devuelva el array ordenado. +- **`10` Remove Vowels:** escribir una función flecha llamada `rapid` que recorra un texto, elimine todas las vocales y ponga el resto en mayúsculas, de modo que `rapid("Wonderful")` devuelva `WNDRFL`. -> Una vez ya tengas abierto VSCode los ejercicios deberían empezar automáticamente, si esto no sucede puedes intentar empezar los ejercicios escribiendo este comando en tu terminal: `$ learnpack start` +Estas son las tres figuras del ejercicio `03` y el motivo de que haya que llamar a `calculateArea()` con `(4, 4)`, `(2, 2)` y `(5, 5)`: -## Instalación local +![Tres cuadrados dibujados uno al lado del otro con sus medidas escritas en los lados: un primer cuadrado de 4 por 4 pulgadas, otro más pequeño de 2 por 2 pulgadas y uno mayor de 5 por 5 pulgadas](https://raw.githubusercontent.com/4GeeksAcademy/javascript-functions-exercises-tutorial/master/.learn/assets/call-a-function.png) -Clona el repositorio en tu ambiente local y sigue los siguientes pasos: +## 🎓 ¿Qué necesitas antes de empezar? -1. Instala LearnPack, el package manager para tutoriales y el plugin compilador de node para LearnPack, asegúrate de tener instalado node.js 14+: +- **Sintaxis básica de JavaScript:** declarar variables con `let` o `const` y entender un `if` sencillo. El ejercicio `01` arranca en `console.log()`, así que no se da por sabido nada más. +- **Ninguna experiencia previa con funciones:** la definición, la sintaxis, los parámetros y el `return` se enseñan desde cero dentro del propio tutorial. +- **Nada que instalar si usas Codespaces:** el contenedor ya instala por ti Node.js 22, Jest y la CLI de LearnPack. +- **Node.js si lo ejecutas en local:** todos los ejercicios corren sobre Node, aquí no hay navegador, ni HTML, ni DOM. -```bash -$ npm i learnpack -g -$ learnpack plugins:install learnpack-node -``` +## ✅ ¿Cómo funciona la corrección automática? -2. Descarga estos ejercicios en particular usando LearnPack y navega con `cd` dentro de la carpeta: +10 de las 11 carpetas tienen fichero de test: nueve se llaman `tests.js` y el de `07-Function-that-returns` se llama `test.js`. Solo `00-Welcome`, que es la pantalla de bienvenida, no tiene. Al pulsar `Run`, LearnPack ejecuta ese fichero con Jest 29.7.0 y te enseña exactamente qué comprobación ha fallado. -```bash -$ learnpack download javascript-functions-exercises-tutorial -$ cd javascript-functions-exercises-tutorial -``` +Los tests miran tres cosas distintas, y saber cuál se ha roto te ahorra mucho tiempo: + +1. **Lo que has impreso.** `console.log` se sustituye por un mock, así que los tests pueden contar cuántas veces lo has llamado y comparar el valor exacto que recibió. + +2. **Tus variables y funciones por su nombre.** El test carga `app.js` con `rewire` y saca los valores de dentro, así que nombres como `superduper`, `squareArea1`, `multi`, `renderPerson`, `sortNames` o `rapid` tienen que coincidir al pie de la letra. + +3. **El código fuente de tu `app.js`.** Varios tests leen el fichero como texto plano y le pasan una expresión regular. Así es como el ejercicio `09` exige `.sort(` y el `10` exige a la vez `const rapid = ... =>` y un bucle `for`. + +> 💡 La corrección es estricta a propósito, pero tómala como una guía y no como un juez. Si un ejercicio te bloquea, abre el menú, sigue adelante y vuelve después. + +## 💡 ¿Qué errores conviene evitar? + +1. **Imprimir cuando el ejercicio espera un `return`.** En el `04`, el `08`, el `09` y el `10` la línea del `console.log()` ya viene escrita al final de `app.js`. Si tu función termina con un print en vez de con `return`, devuelve `undefined` y las comprobaciones fallan aunque la consola se vea bien. + +2. **Escribir la palabra `function` en el ejercicio `06`.** El test pasa la regex `/function/gm` por todo el fichero y falla si aparece en cualquier sitio, comentarios incluidos. Además comprueba que `multi.prototype` sea `undefined`, así que solo pasa una función flecha de verdad. + +3. **Declarar `rapid` con `let` en el ejercicio `10`.** La expresión regular espera `const rapid = ... =>`, y otro test exige un bucle `for`, de modo que resolverlo con `replace()` y sin bucle tampoco pasa. + +4. **No dejar los números literales en el código.** Los ejercicios `02`, `03` y `05` buscan en tu fichero las llamadas tal cual: `sum(3445324, 53454423)`, `calculateArea(4, 4)`, `calculateArea(2, 2)`, `calculateArea(5, 5)` y `multi(324234, 47)`. Calcular el resultado a mano y asignarlo directamente no cuenta. + +5. **Dejarte `console.log()` de depuración.** Los ejercicios `01`, `05`, `06`, `07` y `08` comprueban que la consola se llamó exactamente una vez. Un print olvidado tumba una solución que por lo demás es correcta. + +6. **Devolver un string donde se espera un número.** Los ejercicios `05` y `06` comparan contra el número `15238998`, así que envolverlo en un template literal o concatenarle cualquier texto hace que la comparación falle. + +7. **Cambiar la frase o el orden de los parámetros en el `08`.** La llamada que ya viene en el fichero es `renderPerson('Bob', '05/22/1983', 'green', 23, 'male')`, es decir: nombre, fecha de nacimiento, color de ojos, edad y género. La frase se compara carácter a carácter, incluidas las palabras `is a`, `years old`, `born in` y `with green eyes`. + +## ❓ Preguntas frecuentes + +### ¿Tengo que instalar algo para empezar? + +No. Al abrir el repositorio en GitHub Codespaces obtienes un contenedor que instala solo Node.js 22, Jest 29.7.0 y la CLI de LearnPack, y los ejercicios se abren dentro de VS Code por su cuenta. La instalación local es opcional y solo necesita Node.js y un par de comandos en la terminal. + +### ¿Cuánto se tarda en terminar los 10 ejercicios? + +El paquete está estimado en 5 horas. Los primeros son ejercicios de dos minutos alrededor de `console.log()` y de llamar a una función ya escrita; los tres últimos (`08` Function Parameters, `09` Array Methods y `10` Remove Vowels) son pequeños algoritmos donde se va la mayor parte del tiempo. -Nota: Una vez que termines de descargarlo, encontrarás una carpeta llamada "exercises" que contiene los ejercicios. +### ¿Qué diferencia hay entre una función normal, una anónima y una flecha? -3. Inicializa el tutorial/exercises ejecutando el siguiente comando al mismo nivel en el que se encuentra tu archivo learn.json: +Una función normal tiene nombre propio: `function multi(a, b) { return a * b; }`. Una anónima no lo tiene, así que solo puedes usarla si la guardas en una variable: `let multi = function(a, b) { return a * b; }`. Una función flecha es la forma corta de esa segunda, `const multi = (a, b) => a * b`, y no crea su propio `this`, que es la razón de que no necesite `.bind()`. Los ejercicios `04`, `05` y `06` recorren la misma multiplicación en los tres estilos: en el `04` la escribes tú, en el `05` te la dan ya hecha como función anónima y en el `06` la conviertes en flecha. + +### ¿Por qué falla el ejercicio si la salida de la consola parece correcta? + +Porque varios tests ni siquiera miran la consola. Unos leen tu código fuente con una expresión regular y otros cargan tus variables con `rewire` y llaman a tu función con valores que tú no probaste, como `multi(4, 12)` en el ejercicio `04` o `rapid("Wonderful")` en el `10`. Lee el nombre de la comprobación que falló: ahí está la pista de cuál de los tres controles se rompió. + +### ¿Están los ejercicios y los vídeos en español? + +Sí. Las 11 carpetas incluyen `README.md` y `README.es.md`, y puedes cambiar de idioma desde el menú de ejercicios sin perder el progreso. La versión en español enlaza un vídeo explicativo para los 10 ejercicios corregidos; la inglesa enlaza 4, los de los ejercicios `01`, `02`, `04` y `05`. + +### ¿Cuesta algo y de quién es el código que escribo? + +Acceder a este repositorio y a sus ejercicios no cuesta nada, y lo que escribas dentro de `app.js` es tuyo. El contenido del tutorial en sí no es open source: se publica con todos los derechos de propiedad intelectual reservados, lo que no permite republicarlo ni redistribuirlo. El texto completo está en [LICENSE.md](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial/blob/HEAD/LICENSE.md). + + +## 📚 Tutoriales relacionados + +Este paquete es el tercer paso de la serie interactiva de JavaScript: + +1. [JavaScript para principiantes](https://4geeks.com/es/interactive-exercise/ejercicios-javascript-para-principiantes) +2. [Arrays y bucles](https://4geeks.com/es/interactive-exercise/javascript-array-loops-exercises-es) +3. **Funciones de JavaScript** ← estás aquí +4. [Domina JavaScript practicando](https://4geeks.com/es/interactive-exercise/master-javascript-exercises-es) + +## 🚀 ¿Cómo empezar? + +Lo más rápido es [abrirlo en GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-functions-exercises-tutorial). El contenedor instala todo y los ejercicios arrancan solos dentro de VS Code. + +Si no arrancan automáticamente, escribe esto en la terminal: ```bash -$ npm i jest@24.8.0 -g -$ learnpack start +learnpack start ``` - -## ¿Cómo están organizados los ejercicios? +También puedes abrir el paquete en [Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial). Usa el menú superior para moverte entre ejercicios y para cambiar las instrucciones entre español e inglés. + +## 💻 Instalación local + +Clona el repositorio y sigue estos pasos: + +1. Instala LearnPack y su plugin compilador de Node.js. Necesitas tener Node.js instalado antes: + + ```bash + npm i @learnpack/learnpack -g + learnpack plugins:install @learnpack/node + ``` -Cada ejercicio es una pequeña aplicación de React que contiene los siguientes archivos: +2. Arranca el tutorial desde la misma carpeta donde está `learn.json`: -1. **app.js:** representa el archivo JavaScript de entrada que ejecutará la computadora. -2. **README.md:** contiene las instrucciones de ejercicio. -3. **test.js:** contiene el script del test para el ejercicio (no es necesario que abras este archivo). + ```bash + learnpack start + ``` -> 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. +Si algo falla, la [guía rápida de LearnPack para estudiantes](https://4geeks.com/docs/learnpack/quickstart-for-learners) repasa la instalación entera. + +## 📝 ¿Cómo están organizados los ejercicios? + +Cada una de las 10 carpetas corregidas dentro de `exercises/` es un pequeño programa de Node.js con estos ficheros: + +- **`app.js`:** el fichero que editas y el punto de entrada que se ejecuta. +- **`README.md`:** las instrucciones en inglés. +- **`README.es.md`:** las mismas instrucciones en español. +- **`tests.js`:** el test de Jest que corrige tu solución, llamado `test.js` en el ejercicio `07`. No hace falta que lo abras. +- **`solution.hide.js`:** una solución que funciona, oculta por LearnPack hasta que la pides. + +`00-Welcome` es la excepción: es solo la pantalla de bienvenida y no contiene más que los dos `README`. + +## 🤝 Colaboradores -## Colaboradores - Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 🤓 (build-tutorial) ✅ (documentación) 📖 +1. [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr): programador 💻, idea 🤔, tests ⚠️, revisión de pull requests 👀, creación del tutorial ✅, documentación 📖 -2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador), (traducción) 🌎 +2. [Paolo (plucodev)](https://github.com/plucodev): reporte de bugs 🐛, programador 💻, traducción 🌎 -3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) 🐛, (translation) 🌎 +3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo): reporte de bugs 🐛, traducción 🌎 -Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! +4. [Luis Rivera (Luis846)](https://github.com/Luis846): programador 💻, tests ⚠️ -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 nuestros [Cursos 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). +Puedes ver la lista completa en el [gráfico de colaboradores](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial/graphs/contributors). Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors) y toda contribución es bienvenida. Si encuentras un error o una errata, repórtalo o manda un pull request. + From 2b82deac7de2d438faf40f9bccaadfe4a50b3236 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20L=C3=B3pez?= <145539062+KrilinZ@users.noreply.github.com> Date: Mon, 3 Aug 2026 14:12:49 +0200 Subject: [PATCH 3/4] docs(readme): rewrite for clarity, SEO and AI answer engines From 76e3740cd0b3f37d886bb450fdde7246c8ea5312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20L=C3=B3pez?= <145539062+KrilinZ@users.noreply.github.com> Date: Mon, 3 Aug 2026 14:12:50 +0200 Subject: [PATCH 4/4] docs(readme): rewrite for clarity, SEO and AI answer engines