From 7fa5759d8eaee7936ce0645d865244bd825ced8c 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:11:16 +0200 Subject: [PATCH 1/4] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.md | 187 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 157 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index a77aafd9c..5ee479dc2 100644 --- a/README.md +++ b/README.md @@ -1,62 +1,189 @@ -# Master JavaScript tutorial at 4Geeks Academy +
-> By [@alesanchezr](https://twitter.com/alesanchezr) and [other contributors](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/graphs/contributors) at [4Geeks Academy](https://4geeksacademy.co/) +# Master Javascript Practicing -*Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/main/README.es.md) :es:* - +[![Certified tutorial](https://img.shields.io/badge/4Geeks-certified%20tutorial-2563eb)](https://4geeks.com/en/interactive-exercise/master-javascript-exercises) +[![Autograded with LearnPack](https://img.shields.io/badge/LearnPack-162%20autograded%20exercises-2563eb)](https://learnpack.co) +[![Open in GitHub Codespaces](https://img.shields.io/badge/Open%20in-GitHub%20Codespaces-fb5a1f?logo=github)](https://codespaces.new/?repo=4GeeksAcademy/master-javascript-programming-exercises) -### 160 exercises about JavaScript +*These instructions are also available in [Spanish](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/HEAD/README.es.md).* -Complete selection of auto-graded and interactive JavaScript exercises, where you will put your problem-solving skills to the test and learn many of the most popular JavaScript methods. +
+ -> One key thing to learn in the world of coding is that the same problem may have multiple valid solutions, the important thing is that you understand the logic and principles behind them. +Master Javascript Practicing is an interactive tutorial with 162 auto-graded JavaScript exercises plus a welcome page. Every exercise carries a Jest suite — 988 test cases in total, an average of 6 per exercise — and a reference solution. It declares 50 hours of work and climbs from a one-line `isOldEnoughToDrink` boolean to binary search, a longest-palindrome finder and a prototype-based phone-number formatter. +## 📋 About this tutorial + +- **Difficulty**: declared as `easy` in [learn.json](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/HEAD/learn.json), but the curve is long: exercise 001 returns `age >= 21` and exercise 154 asks for the longest palindrome inside a sentence. +- **Duration**: 50 hours (`"duration": 50` in learn.json). +- **Exercises**: 163 folders inside [`exercises/`](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/tree/HEAD/exercises) — 1 welcome page and 162 coding exercises numbered 001 to 155, with no gaps (some numbers are split into `142.1`, `143.2`, `155.4` and so on). +- **Automatic grading**: yes, `"graded": true` and `"grading": "isolated"`. All 162 coding exercises ship a `test.js` Jest suite, 988 test cases in total. +- **Technologies**: plain JavaScript on Node.js 22, Jest 29.7.0 and the `rewire` module, orchestrated by LearnPack 5.0.348 with the `@learnpack/node` plugin 1.1.15. +- **Video solutions**: none (`"videoSolutions": false`), but all 162 coding exercises ship a hidden reference solution file. +- **Instructions available in**: [English](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/HEAD/README.md) and [Español](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/HEAD/README.es.md) — all 163 folders carry both a `README.md` and a `README.es.md`. + + +## 🎯 What will you learn? + +The exercises are ordered so each block reuses the previous one. Counting across the 162 reference solutions: + +- **Writing functions that return, not print.** Almost every exercise is "declare a function that, given X, returns Y"; a dozen ask you to modify the object you were handed instead. Either way, nothing is ever graded from what you print. +- **Booleans and operators**: `>`, `<`, `===`, `%`, `&&`, `||` and negation, in the 001–028 block (`isEven`, `isOdd`, `areBothOdd`, `isEitherEven`, `isEvenAndGreaterThanTen`). +- **Object literals**: reading a key, adding one, and deleting one. The `delete` operator appears in 9 reference solutions; `hasOwnProperty` in 2. +- **The `Math` object**: `Math.PI`, `Math.pow`, `Math.sqrt`, `Math.abs`, `Math.floor`, `Math.min` and `Math.max` appear across 9 reference solutions — five of them in the circle-and-powers block 042–046, the rest in `findMinLengthOfThreeWords`, `findMaxLengthOfThreeWords`, `multiply` and the binary search. +- **Array methods**: counting calls across the reference solutions, `push` appears 19 times, `map` 13, `filter` 10, `slice` 9, `split` 7, `join` 5 and `forEach` 5, plus `shift`, `unshift`, `pop`, `splice`, `concat`, `reverse`, `reduce` and `Array.isArray` (17). +- **Every loop shape**: 22 solutions use the classic counted `for`, 19 use `for...of`, 12 use `for...in` and 3 use `while`. 24 use arrow functions, so you get to compare both styles on the same kind of problem. +- **Nested data**: objects whose values are arrays (exercises 092–110) and arrays of objects that contain arrays of objects (the four `155-FashionInventory` exercises). +- **Type checking**: `typeof` appears in 11 solutions — filtering an object's values by type in the 067–075 block, and picking out only the strings or only the numbers from an array holding both in exercises 124–127. +- **Classic algorithms**: binary search, palindrome detection, string rotation, isograms, outlier detection and pair-sum searching (exercises 148–154). +- **Prototype-based objects**: exercise 153 hands you a constructor function with six `prototype` methods — two of them already written — and asks you to fill in the other four. + +Some things are deliberately out of scope. Across every `README.md`, `app.js`, `test.js` and reference solution in the repository — 649 files — there is not a single ES6 `class`, `async`, `await`, `Promise`, `fetch`, `document.` or `.sort()`. This is pure language practice: no DOM, no browser, no network. + +## 👀 What will you build? + +162 small functions, each in its own numbered folder, each verified by its own test file. The blocks: + +**001–049 — conditionals, strings and arithmetic (49 exercises).** `checkAge('Adrian', 21)` must return the exact string `'Welcome, Adrian!'` and `checkAge('Adrian', 20)` the exact string `'Go home, Adrian!'`. Then `getFullName`, `isSameLength`, `computeAverageLengthOfWords`, and the geometry set: area and perimeter of rectangles, triangles and circles, `computePower`, `computeSquareRoot`, `doubleSquareRootOf`. + +**050–091 — arrays, strings and object surgery (42 exercises).** Getting the nth, first and last element; `getElementsAfter` and `getElementsUpTo`; the paired exercises that force you to notice the difference between mutating and copying (`removeFromFront` vs `removeFromFrontOfNew`, `addToBack` vs `addToBackOfNew`). `extend` copies the second object's properties into the first *without* overwriting existing keys, and eight `remove…` exercises delete properties by type or by value. Also `countCharacter`, `getAllLetters`, `getAllWords`, `convertDoubleSpaceToSingle`, and `keep([1, 2, 3, 2, 1], 2)` returning `[2, 2]`. + +**092–127 — nested data and whole-array algorithms (36 exercises).** Eighteen exercises reach inside an object to work on an array stored at a key: `getAverageOfElementsAtProperty`, `getSquaredElementsAtProperty`, `getProductOfAllElementsAtProperty`. `select(['a', 'c', 'e'], {a: 1, b: 2, c: 3, d: 4})` must return `{ a: 1, c: 3 }` and ignore keys that are not in both. Then `countAllCharacters`, `joinArrayOfArrays` on a matrix, and four exercises on arrays holding strings *and* numbers at once, where you have to filter by type before comparing. + +**128–141 — numbers and reasoning (14 exercises).** `calculateBillTotal(20)` must return exactly `24.9` (9.5% tax and 15% tip, each applied to the original amount). `computeCompoundInterest(1500, 0.043, 4, 6)` must return `438.83682213410543`, unrounded. `convertScoreToGrade(104)` must return `'INVALID SCORE'`. Then factorial, digit sums, and the trio that bans the operator you would normally reach for: `modulo`, `isOddWithoutModulo` and `isEvenWithoutModulo`. + +**142.1–143.3 — shape conversions (6 exercises).** `transformFirstAndLast(['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'])` returns `{ Queen: 'Beyonce' }`. `transformEmployeeData` turns an array of key/value pairs into an array of objects, and `convertObjectToList` does the reverse. + +**144–155.4 — the hard block (15 exercises).** `flipEveryNChars('a short example', 5)` returns `'ohs axe trelpma'`. `detectOutlierValue('2 4 7 8 10')` returns `3`, the 1-indexed position of the only odd number. `findPairForSum([3, 34, 4, 12, 5, 2], 9)` returns `[4, 5]`. `search([1, 3, 16, 22, 31, 33, 34], 31)` returns `4` using binary search, and `null` when the value is absent. `isIsogram('Cactus')` returns `false`. `PhoneNumberFormatter([6, 5, 0, 8, 3, 5, 9, 1, 7, 2]).render()` returns `'(650) 835-9172'`. `findLongestPalindrome('My dad is a racecar athlete')` returns `'a racecar a'`. And the four fashion-inventory exercises walk an array of designers, each with an array of shoes, to produce a matrix, a per-designer average price, a filtered matrix and a word-index report. + +## 🎓 What do you need before starting? + +Nothing installed, if you open the repository in GitHub Codespaces: the dev container provisions Node.js 22, Jest and the LearnPack Node plugin by itself. + +What you do need is prior JavaScript. The welcome page states it plainly: this is the last set in a series, and it points you at the three that come first. + +- [JavaScript for beginners](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial) — variables, types, conditionals. +- [Arrays](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial) — indexing, loops over lists. +- [Functions](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial) — parameters, `return`, scope. + +If you can already declare a function and loop over an array, start here. Exercise 001 is still a single comparison, so the on-ramp is gentle even though the last block is not. + +## ✅ How does the automatic grading work? + +Each exercise folder holds a `test.js` file written with Jest. The suite never reads what your file prints: it uses [`rewire`](https://github.com/jhnns/rewire) to reach inside `app.js` and pull out your function by name, like this: + +```js +const rewire = require('rewire'); +const keep = rewire('./app.js').__get__('keep'); +``` + +From there, each `test()` block calls your function and inspects the value it hands back. A typical suite has four to six checks that escalate: the function exists, it returns something, it returns the right type, and then two or three real cases. The shortest suites run 3 checks — exercise 006 is one of the eight that do — and the longest is exercise 153 with 18, which exercises each of the six prototype methods before checking the final rendered string. -## One click installation (recommended): +Grading is `"isolated"`, so each exercise is evaluated on its own and a failure in one never blocks another. -You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/master-javascript-programming-exercises) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/master-javascript-programming-exercises). +> 💡 Two of the 162 exercises grade more than one function at a time: `128-averageIntegers` extracts both `sum` and `average`, and `154-longestPalindrome` extracts `reverseString`, `isPalindrome` and `findLongestPalindrome`. Leaving any of the skeleton's functions empty fails the suite even if your main function is correct. -> Once you have VSCode open, if exercises don't run automatically you can try typing on your terminal: `$ learnpack start` +## 💡 What mistakes should you avoid? -## Local Installation (only if needed) +- **Printing instead of returning.** 100 of the 162 `app.js` files end with a `console.log(...)` demo line. That line is there so you can see your output while you work; the tests never read stdout. `keep([1, 2, 3, 2, 1], 2)` has to *return* `[2, 2]`. +- **Renaming the function, or trusting the folder name.** `rewire(...).__get__('name')` fails outright if the name does not match, and in 20 folders the folder name is not the function name. `012-isLessThanThirty` wants `isLessThan30`; `096-getElementsLessThanOneHundredAtProperty` wants `getElementsLessThan100AtProperty`; `123-joinArraysOfArrays` wants `joinArrayOfArrays` (singular "Array"); `134-convertScoreToGradeWithPlus` wants `convertScoreToGradeWithPlusAndMinus`; `152-isogram` wants `isIsogram`; `154-longestPalindrome` wants `findLongestPalindrome`. Always read the function name from the instructions or from the skeleton in `app.js`. +- **Returning a copy when the test inspects the original.** Twelve suites assert on the object you were handed rather than on a copy you build: `030`, `031`, `037`, `066`, `067`, `068`, `069`, `070`, `072`, `073`, `074` and `075`. Those exercises must mutate in place. Ten of them never look at your return value at all; `030` and `037` check it too, so in those two you must mutate *and* return the object. +- **Reaching for `Object.assign` in exercise 066.** `extend` must not overwrite a key the first object already has: with `{a: 74, b: 22}` and `{b: 2227, c: 91}`, the expected result is `{a: 74, b: 22, c: 91}`, keeping `b: 22`. +- **Rounding money.** `calculateBillTotal(20)` is compared with `toBe(24.9)` and `calculateBillTotal(36)` with `toBe(44.82)`, so apply each rate separately to the original amount and do not round. Same in exercise 137, where the expected value carries all 14 decimals of `438.83682213410543`. +- **Getting exact strings almost right.** `convertScoreToGrade` returns `'INVALID SCORE'` in capitals for anything outside 0–100. `greetCustomer('Joe')` must return `"Welcome back, Joe! We're glad you liked us the first time!"` with a straight apostrophe, and `greetCustomer('Carl')` — a name that is not in `customerData` — must return `'Welcome! Is this your first time?'`. +- **Sorting before searching in exercise 149.** `findPairForSum` is expected to scan left to right: with `[3, 34, 4, 12, 5, 2]` and target 9 the answer is `[4, 5]`, but adding a `6` at the end makes the answer `[3, 6]`, because 3 now finds a partner earlier in the scan. +- **Assuming exercise 154 gets clean input.** Its instructions promise "only letters", yet the second test case is `"Madam, i'm adam"` and the expected answer is `'Madam'` — capital M preserved. Compare case-insensitively, but return the substring exactly as it appears in the original string. +- **Skipping the provided helpers.** Exercises 128, 153 and 154 give you a skeleton with several functions and the tests check every one of them individually. -Clone the repository in your local environment and follow the steps below: +## ❓ Frequently asked questions -1. Install LearnPack, the package manager for learning tutorials and the node compiler plugin for learnpack, make sure you also have node.js 14: +### How long does it take to finish these JavaScript exercises? + +`learn.json` declares 50 hours. Spread across 162 exercises that averages about 18 minutes each, but the distribution is heavily skewed: the first fifty exercises are one-liners you can clear in two or three minutes, while a single exercise in the 148–155 block can eat an hour. + +### Do I need to know JavaScript before starting? + +Yes, the basics. The welcome page says this is the last of a series and links to the beginner, arrays and functions tutorials that come before it. You do not need any object-oriented background: exercise 153 is the only one that uses a constructor function, and it comes with the skeleton already written. + +### How many exercises are actually auto-graded? + +All 162 coding exercises, adding up to 988 Jest test cases and 1,009 assertions. The only folder without a test is `00-Welcome`, which is an intro page rather than an exercise. 109 of the 163 folders also include a hints section, and 161 include a worked example showing the expected output. + +### Do I have to install anything on my computer? + +No. Opening the repository in Codespaces gives you a ready-made container with Node.js 22, Jest 29.7.0 and LearnPack already installed. A local setup is possible and documented below if you prefer working on your own machine. + +### Are there solutions I can compare against? + +Yes, but no videos. `learn.json` sets `videoSolutions` to `false`. Instead, each of the 162 coding folders ships a hidden reference solution file next to `app.js`. Read it after you have solved the exercise — the same problem usually has several valid answers, and the reference is only one of them. + +### Is practising this many small functions still worth it? + +These 162 problems train the mechanics that show up in any code review: deciding whether to mutate or copy, picking `map` versus `filter` versus `reduce`, walking a nested structure without losing track of which level you are on, and matching an exact return contract. What this set does *not* cover is asynchronous JavaScript, the DOM or modules, so plan a separate tutorial for those. + + +## 🚀 How to start + +The fastest path is one click: [open this tutorial in GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/master-javascript-programming-exercises). There is also a [Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/master-javascript-programming-exercises) alternative. + +Once VS Code is open, the LearnPack exercises should start on their own. If they do not, run this in the terminal: ```bash -$ npm i @learnpack/learnpack -g +learnpack start ``` -2. Start the tutorial/exercises by running the following command at the same level where your learn.json file is: +## 💻 Local installation + +**Step 1.** Install LearnPack, the Node plugin and Jest, using the same versions the dev container provisions: ```bash -$ learnpack start +npm i @learnpack/learnpack@5.0.348 -g && learnpack plugins:install @learnpack/node@1.1.15 +npm i jest@29.7.0 jest-environment-jsdom@29.7.0 -g ``` - -## How are the exercises organized? +**Step 2.** Clone the repository and move into it: + +```bash +git clone https://github.com/4GeeksAcademy/master-javascript-programming-exercises.git +cd master-javascript-programming-exercises +``` + +**Step 3.** Start the tutorial from the same folder as `learn.json`: + +```bash +learnpack start +``` -Each exercise is a small React application containing the following files: +## 📚 How the exercises are organized -1. **app.js**: Represents the entry JavaScript file that will be executed by the computer. -2. **README.md**: Contains exercise instructions. -3. **test.js**: Contains the testing script for the exercise (you don't have to open this file). +Each exercise is a folder inside `exercises/` and contains these files: -> 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. +- `app.js` — the file you edit and the one the computer runs. Present in all 162 coding exercises. +- `README.md` — the instructions, in English. +- `README.es.md` — the same instructions in Spanish. Present in all 163 folders. +- `test.js` — the Jest suite. You never open it. Present in all 162 coding exercises. +- A hidden solution file — the reference answer. Present in all 162 coding exercises, named `solution.hide.js` everywhere except `011-isGreaterThanTen`, where the file is called `solutions.hide.js`. -## Contributors +The folder `00-Welcome` holds only the two READMEs: it is the intro page, not an exercise. -Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +Found a bug or a typo? Open an issue in [this repository](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/issues) — the exercises were built collaboratively and reports are welcome. -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 👀 (build-tutorial) ✅ (documentation) 📖 +## 🤝 Contributors -2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, contribution: (coder), (translation) 🌎 +The tutorial was started by [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), and these are the people with the most commits in the repository today: -3. [Ricardo Rodriguez (RickRodriguez8080)](https://github.com/RickRodriguez8080) contribution: (build-tutorial) ✅, (documentation) 📖 +- [Jose Mora (josemoracard)](https://github.com/josemoracard) — 1,196 commits +- [Tomas Gonzalez (tommygonzaleza)](https://github.com/tommygonzaleza) — 367 commits +- [Martín Suárez (kiddopro)](https://github.com/kiddopro) — 110 commits +- [Elvira Quiroz (ElviraQDP)](https://github.com/ElviraQDP) — 105 commits +- [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr) — 96 commits +- [Ernesto Gonzalez (UmiKami)](https://github.com/UmiKami) — 43 commits +- [Paolo Lucano (plucodev)](https://github.com/plucodev) — 39 commits -This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! +Plus [everyone else in the contributors graph](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/graphs/contributors). This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)), and contributions of any kind are welcome. -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). +This tutorial is one of many built by students and teachers at [4Geeks Academy](https://4geeks.com). + From a6b2c427fa264a588aaccb2cb84cc58a21837108 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:11:18 +0200 Subject: [PATCH 2/4] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.es.md | 188 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 158 insertions(+), 30 deletions(-) diff --git a/README.es.md b/README.es.md index 5146f9f24..e82c01003 100644 --- a/README.es.md +++ b/README.es.md @@ -1,61 +1,189 @@ -# Tutorial Master JavaScript de 4Geeks Academy +
-> Por [@alesanchezr](https://twitter.com/alesanchezr) y [otros colaboradores](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/graphs/contributors) de [4Geeks Academy](https://4geeksacademy.com/) - +# Domina Javascript Practicando + +[![Tutorial certificado](https://img.shields.io/badge/4Geeks-tutorial%20certificado-2563eb)](https://4geeks.com/es/interactive-exercise/master-javascript-exercises-es) +[![Autocorregido con LearnPack](https://img.shields.io/badge/LearnPack-162%20ejercicios%20autocorregidos-2563eb)](https://learnpack.co) +[![Abrir en GitHub Codespaces](https://img.shields.io/badge/Abrir%20en-GitHub%20Codespaces-fb5a1f?logo=github)](https://codespaces.new/?repo=4GeeksAcademy/master-javascript-programming-exercises) -### 160 ejercicios de JavaScript +*Estas instrucciones también están disponibles en [inglés](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/HEAD/README.md).* -Selección completa de ejercicios de JavaScript interactivos y con calificación automática, donde pondrás tus habilidades de resolución de problemas al límite y aprenderás muchos de los métodos más populares de JavaScript. +
+ -> Un punto clave para aprender en el mundo de la programación es que el mismo problema puede tener varias soluciones válidas, lo importante que debes entender es la lógica y los principios detrás de cada solución. +Domina Javascript Practicando es un tutorial interactivo con 162 ejercicios de JavaScript autocorregidos, más una página de bienvenida. Cada ejercicio trae su batería de tests con Jest —988 casos de prueba en total, una media de 6 por ejercicio— y su solución de referencia. Declara 50 horas de trabajo y va desde un `isOldEnoughToDrink` de una línea hasta una búsqueda binaria, el palíndromo más largo de una frase y un formateador de teléfonos con prototipos. +## 📋 Ficha del tutorial + +- **Dificultad**: declarada como `easy` en [learn.json](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/HEAD/learn.json), aunque la curva es larga: el ejercicio 001 devuelve `age >= 21` y el 154 pide encontrar el palíndromo más largo dentro de una frase. +- **Duración**: 50 horas (`"duration": 50` en learn.json). +- **Ejercicios**: 163 carpetas dentro de [`exercises/`](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/tree/HEAD/exercises) — 1 página de bienvenida y 162 ejercicios numerados del 001 al 155, sin huecos (algunos números se dividen en `142.1`, `143.2`, `155.4`, etc.). +- **Corrección automática**: sí, `"graded": true` y `"grading": "isolated"`. Los 162 ejercicios de código traen un `test.js` con Jest, 988 casos de prueba en total. +- **Tecnologías**: JavaScript puro sobre Node.js 22, Jest 29.7.0 y el módulo `rewire`, orquestado por LearnPack 5.0.348 con el plugin `@learnpack/node` 1.1.15. +- **Soluciones en vídeo**: no hay (`"videoSolutions": false`), pero los 162 ejercicios de código incluyen un fichero oculto con la solución de referencia. +- **Instrucciones disponibles en**: [español](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/HEAD/README.es.md) e [inglés](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/blob/HEAD/README.md) — las 163 carpetas tienen su `README.md` y su `README.es.md`. + + +## 🎯 ¿Qué vas a aprender? + +Los ejercicios están ordenados de forma que cada bloque reutiliza el anterior. Contando sobre las 162 soluciones de referencia: + +- **Escribir funciones que devuelven, no que imprimen.** Casi todos los ejercicios son «declara una función que, dado X, retorne Y»; una docena te piden modificar el objeto que recibes. En ningún caso se corrige lo que imprimes por consola. +- **Booleanos y operadores**: `>`, `<`, `===`, `%`, `&&`, `||` y la negación, en el bloque 001–028 (`isEven`, `isOdd`, `areBothOdd`, `isEitherEven`, `isEvenAndGreaterThanTen`). +- **Objetos literales**: leer una clave, añadir otra y borrarla. El operador `delete` aparece en 9 soluciones de referencia y `hasOwnProperty` en 2. +- **El objeto `Math`**: `Math.PI`, `Math.pow`, `Math.sqrt`, `Math.abs`, `Math.floor`, `Math.min` y `Math.max` salen en 9 soluciones de referencia: cinco en el bloque de círculos y potencias 042–046, y el resto en `findMinLengthOfThreeWords`, `findMaxLengthOfThreeWords`, `multiply` y la búsqueda binaria. +- **Métodos de array**: contando llamadas en las soluciones de referencia, `push` aparece 19 veces, `map` 13, `filter` 10, `slice` 9, `split` 7, `join` 5 y `forEach` 5, además de `shift`, `unshift`, `pop`, `splice`, `concat`, `reverse`, `reduce` y `Array.isArray` (17). +- **Todas las formas de iterar**: 22 soluciones usan el `for` clásico con contador, 19 usan `for...of`, 12 usan `for...in` y 3 usan `while`. En 24 aparecen funciones flecha, así que puedes comparar los dos estilos sobre el mismo tipo de problema. +- **Datos anidados**: objetos cuyos valores son arrays (ejercicios 092–110) y arrays de objetos que a su vez contienen arrays de objetos (los cuatro ejercicios `155-FashionInventory`). +- **Comprobación de tipos**: `typeof` aparece en 11 soluciones: para filtrar por tipo los valores de un objeto en el bloque 067–075, y para quedarse solo con los textos o solo con los números de un array que mezcla ambos en los ejercicios 124–127. +- **Algoritmos clásicos**: búsqueda binaria, detección de palíndromos, rotación de cadenas, isogramas, detección del valor atípico y búsqueda del par que suma un objetivo (ejercicios 148–154). +- **Objetos con prototipos**: el ejercicio 153 te entrega una función constructora con seis métodos en su `prototype` —dos ya escritos— y te pide rellenar los otros cuatro. + +Hay cosas que quedan fuera a propósito. En los 649 ficheros del repositorio (`README.md`, `app.js`, `test.js` y soluciones) no aparece ni una sola `class` de ES6, ni `async`, ni `await`, ni `Promise`, ni `fetch`, ni `document.`, ni `.sort()`. Esto es práctica de lenguaje puro: sin DOM, sin navegador y sin red. + +## 👀 ¿Qué vas a construir? + +162 funciones pequeñas, cada una en su carpeta numerada y con su fichero de tests. Los bloques: + +**001–049 — condicionales, cadenas y aritmética (49 ejercicios).** `checkAge('Adrian', 21)` tiene que devolver exactamente `'Welcome, Adrian!'` y `checkAge('Adrian', 20)`, exactamente `'Go home, Adrian!'`. Después llegan `getFullName`, `isSameLength`, `computeAverageLengthOfWords` y el bloque de geometría: área y perímetro de rectángulos, triángulos y círculos, `computePower`, `computeSquareRoot` y `doubleSquareRootOf`. + +**050–091 — arrays, cadenas y cirugía de objetos (42 ejercicios).** Obtener el elemento n-ésimo, el primero y el último; `getElementsAfter` y `getElementsUpTo`; y las parejas de ejercicios que te obligan a distinguir entre modificar y copiar (`removeFromFront` frente a `removeFromFrontOfNew`, `addToBack` frente a `addToBackOfNew`). `extend` copia las propiedades del segundo objeto en el primero *sin* pisar las claves que ya existen, y ocho ejercicios `remove…` borran propiedades según su tipo o su valor. También `countCharacter`, `getAllLetters`, `getAllWords`, `convertDoubleSpaceToSingle` y `keep([1, 2, 3, 2, 1], 2)`, que devuelve `[2, 2]`. + +**092–127 — datos anidados y algoritmos sobre arrays completos (36 ejercicios).** Dieciocho ejercicios entran en un objeto para trabajar con el array guardado en una de sus claves: `getAverageOfElementsAtProperty`, `getSquaredElementsAtProperty`, `getProductOfAllElementsAtProperty`. `select(['a', 'c', 'e'], {a: 1, b: 2, c: 3, d: 4})` tiene que devolver `{ a: 1, c: 3 }` e ignorar las claves que no estén en los dos sitios. Después vienen `countAllCharacters`, `joinArrayOfArrays` sobre una matriz y cuatro ejercicios con arrays que mezclan textos *y* números, donde hay que filtrar por tipo antes de comparar. + +**128–141 — números y razonamiento (14 ejercicios).** `calculateBillTotal(20)` tiene que devolver exactamente `24.9` (9,5 % de impuestos y 15 % de propina, cada uno aplicado sobre el importe original). `computeCompoundInterest(1500, 0.043, 4, 6)` tiene que devolver `438.83682213410543`, sin redondear. `convertScoreToGrade(104)` tiene que devolver `'INVALID SCORE'`. Y luego el factorial, la suma de dígitos y el trío que te prohíbe el operador que usarías por instinto: `modulo`, `isOddWithoutModulo` e `isEvenWithoutModulo`. + +**142.1–143.3 — cambios de forma (6 ejercicios).** `transformFirstAndLast(['Queen', 'Elizabeth', 'Of Hearts', 'Beyonce'])` devuelve `{ Queen: 'Beyonce' }`. `transformEmployeeData` convierte un array de pares clave/valor en un array de objetos, y `convertObjectToList` hace el camino inverso. + +**144–155.4 — el bloque duro (15 ejercicios).** `flipEveryNChars('a short example', 5)` devuelve `'ohs axe trelpma'`. `detectOutlierValue('2 4 7 8 10')` devuelve `3`, la posición (empezando en 1) del único número impar. `findPairForSum([3, 34, 4, 12, 5, 2], 9)` devuelve `[4, 5]`. `search([1, 3, 16, 22, 31, 33, 34], 31)` devuelve `4` con búsqueda binaria, y `null` cuando el valor no está. `isIsogram('Cactus')` devuelve `false`. `PhoneNumberFormatter([6, 5, 0, 8, 3, 5, 9, 1, 7, 2]).render()` devuelve `'(650) 835-9172'`. `findLongestPalindrome('My dad is a racecar athlete')` devuelve `'a racecar a'`. Y los cuatro ejercicios del catálogo de moda recorren un array de diseñadores, cada uno con su array de zapatos, para producir una matriz, un precio medio por diseñador, una matriz filtrada y un informe con índices de palabras. + +## 🎓 ¿Qué necesitas saber antes de empezar? + +No necesitas instalar nada si abres el repositorio en GitHub Codespaces: el contenedor de desarrollo levanta Node.js 22, Jest y el plugin de LearnPack para Node por su cuenta. + +Lo que sí necesitas es JavaScript previo. La página de bienvenida lo dice sin rodeos: esta es la última tanda de una serie, y te remite a las tres anteriores. + +- [JavaScript para principiantes](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial) — variables, tipos, condicionales. +- [Arreglos](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial) — índices y bucles sobre listas. +- [Funciones](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial) — parámetros, `return`, ámbito. + +Si ya sabes declarar una función y recorrer un array, puedes empezar aquí directamente. El ejercicio 001 sigue siendo una sola comparación, así que la entrada es suave aunque el final no lo sea. + +## ✅ ¿Cómo funciona la corrección automática? + +Cada carpeta de ejercicio incluye un `test.js` escrito con Jest. La batería nunca lee lo que tu fichero imprime: usa [`rewire`](https://github.com/jhnns/rewire) para meterse dentro de `app.js` y sacar tu función por su nombre, así: + +```js +const rewire = require('rewire'); +const keep = rewire('./app.js').__get__('keep'); +``` + +A partir de ahí, cada bloque `test()` llama a tu función y examina el valor que devuelve. Una batería típica tiene entre cuatro y seis comprobaciones que van subiendo de nivel: que la función existe, que devuelve algo, que devuelve el tipo correcto y, por último, dos o tres casos reales. Las baterías más cortas tienen 3 comprobaciones —el ejercicio 006 es uno de los ocho que se quedan ahí— y la más larga es la del 153, con 18, que recorre los seis métodos del prototipo antes de comprobar la cadena final. -## Instalación en un clic (recomendado) +La corrección es `"isolated"`, así que cada ejercicio se evalúa por separado y un fallo nunca bloquea al siguiente. -Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/master-javascript-programming-exercises) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/master-javascript-programming-exercises). +> 💡 Dos de los 162 ejercicios corrigen varias funciones a la vez: `128-averageIntegers` extrae `sum` y `average`, y `154-longestPalindrome` extrae `reverseString`, `isPalindrome` y `findLongestPalindrome`. Si dejas vacía cualquiera de las funciones del esqueleto, la batería falla aunque tu función principal sea correcta. -> 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` +## 💡 ¿Qué errores conviene evitar? -## Instalación local +- **Imprimir en lugar de retornar.** 100 de los 162 ficheros `app.js` terminan con una línea `console.log(...)` de ejemplo. Esa línea está ahí para que veas tu resultado mientras trabajas, pero los tests nunca leen la salida por consola. `keep([1, 2, 3, 2, 1], 2)` tiene que *devolver* `[2, 2]`. +- **Cambiar el nombre de la función, o fiarte del nombre de la carpeta.** `rewire(...).__get__('nombre')` falla en seco si el nombre no coincide, y en 20 carpetas el nombre de la carpeta no es el de la función. `012-isLessThanThirty` pide `isLessThan30`; `096-getElementsLessThanOneHundredAtProperty` pide `getElementsLessThan100AtProperty`; `123-joinArraysOfArrays` pide `joinArrayOfArrays` (en singular); `134-convertScoreToGradeWithPlus` pide `convertScoreToGradeWithPlusAndMinus`; `152-isogram` pide `isIsogram`; y `154-longestPalindrome` pide `findLongestPalindrome`. Saca siempre el nombre de las instrucciones o del esqueleto de `app.js`. +- **Devolver una copia cuando el test mira el original.** Doce baterías comprueban el objeto que recibiste, no la copia que construyas: `030`, `031`, `037`, `066`, `067`, `068`, `069`, `070`, `072`, `073`, `074` y `075`. Esos ejercicios hay que resolverlos modificando el objeto in situ. Diez de ellos ni siquiera miran lo que retornas; el `030` y el `037` sí lo miran, así que en esos dos tienes que modificar *y* devolver el objeto. +- **Tirar de `Object.assign` en el ejercicio 066.** `extend` no puede pisar una clave que el primer objeto ya tenga: con `{a: 74, b: 22}` y `{b: 2227, c: 91}`, el resultado esperado es `{a: 74, b: 22, c: 91}`, conservando `b: 22`. +- **Redondear el dinero.** `calculateBillTotal(20)` se compara con `toBe(24.9)` y `calculateBillTotal(36)` con `toBe(44.82)`, así que aplica cada porcentaje por separado sobre el importe original y no redondees. Lo mismo en el 137, donde el valor esperado arrastra los 14 decimales de `438.83682213410543`. +- **Quedarte a un carácter del texto exacto.** `convertScoreToGrade` devuelve `'INVALID SCORE'` en mayúsculas para cualquier nota fuera de 0–100. `greetCustomer('Joe')` tiene que devolver `"Welcome back, Joe! We're glad you liked us the first time!"` con apóstrofo recto, y `greetCustomer('Carl')` —un nombre que no está en `customerData`— tiene que devolver `'Welcome! Is this your first time?'`. +- **Ordenar antes de buscar en el ejercicio 149.** Se espera que `findPairForSum` recorra el array de izquierda a derecha: con `[3, 34, 4, 12, 5, 2]` y objetivo 9 la respuesta es `[4, 5]`, pero si añades un `6` al final la respuesta pasa a ser `[3, 6]`, porque el 3 encuentra pareja antes en el recorrido. +- **Dar por bueno el enunciado del 154.** Sus instrucciones prometen «solo letras», pero el segundo caso de prueba es `"Madam, i'm adam"` y la respuesta esperada es `'Madam'`, con la M mayúscula intacta. Compara ignorando mayúsculas, pero devuelve el fragmento tal y como aparece en la cadena original. +- **Ignorar las funciones auxiliares que te dan.** Los ejercicios 128, 153 y 154 traen un esqueleto con varias funciones y los tests las comprueban todas por separado. -Clona el repositorio en tu ambiente local y sigue los siguientes pasos: +## ❓ Preguntas frecuentes -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: +### ¿Cuánto se tarda en terminar estos ejercicios de JavaScript? + +El `learn.json` declara 50 horas. Repartidas entre 162 ejercicios salen unos 18 minutos de media, pero el reparto real es muy desigual: los primeros cincuenta son de una línea y se despachan en dos o tres minutos, mientras que un solo ejercicio del bloque 148–155 puede llevarte una hora. + +### ¿Hace falta saber JavaScript antes de empezar? + +Sí, lo básico. La página de bienvenida deja claro que esta es la última tanda de una serie y enlaza los tutoriales de principiantes, arrays y funciones que van antes. Lo que no hace falta es saber programación orientada a objetos: el 153 es el único ejercicio con función constructora y viene con el esqueleto ya escrito. + +### ¿Cuántos ejercicios se corrigen solos de verdad? + +Los 162 ejercicios de código, con 988 casos de prueba de Jest y 1.009 aserciones en total. La única carpeta sin tests es `00-Welcome`, que es la página de introducción y no un ejercicio. Además, 109 de las 163 carpetas incluyen sección de pistas y 161 traen un ejemplo resuelto con la salida esperada. + +### ¿Tengo que instalar algo en mi ordenador? + +No. Abrir el repositorio en Codespaces te da un contenedor listo con Node.js 22, Jest 29.7.0 y LearnPack ya instalados. La instalación local también es posible y está documentada más abajo, por si prefieres trabajar en tu propia máquina. + +### ¿Hay soluciones con las que comparar mi respuesta? + +Sí, aunque no en vídeo: `learn.json` deja `videoSolutions` en `false`. Lo que sí hay es un fichero oculto con la solución de referencia junto al `app.js` de cada uno de los 162 ejercicios. Léelo *después* de resolverlo: un mismo problema suele tener varias soluciones válidas y la de referencia es solo una de ellas. + +### ¿Sigue mereciendo la pena practicar tantas funciones pequeñas? + +Estos 162 problemas entrenan justo lo que aparece en cualquier revisión de código: decidir si conviene modificar o copiar, elegir entre `map`, `filter` y `reduce`, recorrer una estructura anidada sin perder de vista en qué nivel estás y cumplir un contrato de retorno al pie de la letra. Lo que este paquete no cubre es JavaScript asíncrono, el DOM ni los módulos, así que para eso tendrás que buscar otro tutorial. + + +## 🚀 Cómo empezar + +Lo más rápido es un clic: [abre este tutorial en GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/master-javascript-programming-exercises). También existe la alternativa de [Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/master-javascript-programming-exercises). + +Cuando se abra VS Code, los ejercicios de LearnPack deberían arrancar solos. Si no lo hacen, ejecuta esto en la terminal: ```bash -$ npm i @learnpack/learnpack -g +learnpack start ``` -2. Inicializa el tutorial/exercises ejecutando el siguiente comando al mismo nivel en el que se encuentra tu archivo learn.json: +## 💻 Instalación local + +**Paso 1.** Instala LearnPack, el plugin de Node y Jest, con las mismas versiones que usa el contenedor de desarrollo: ```bash -$ learnpack start +npm i @learnpack/learnpack@5.0.348 -g && learnpack plugins:install @learnpack/node@1.1.15 +npm i jest@29.7.0 jest-environment-jsdom@29.7.0 -g ``` - +**Paso 2.** Clona el repositorio y entra en él: + +```bash +git clone https://github.com/4GeeksAcademy/master-javascript-programming-exercises.git +cd master-javascript-programming-exercises +``` + +**Paso 3.** Arranca el tutorial desde la misma carpeta donde está `learn.json`: + +```bash +learnpack start +``` -## ¿Cómo están organizados estos ejercicios? +## 📚 Cómo están organizados los ejercicios -Cada ejercicio es una pequeña aplicación de React que contiene los siguientes archivos: +Cada ejercicio es una carpeta dentro de `exercises/` y contiene estos ficheros: -- **app.js**: Representa el archivo JavaScript de entrada que ejecutará la computadora. -- **README.md**: Contiene las instrucciones del ejercicio. -- **test.js**: Contiene el script del test para el ejercicio (no es necesario que abras este archivo). +- `app.js` — el fichero que editas y el que ejecuta el ordenador. Está en los 162 ejercicios de código. +- `README.md` — las instrucciones, en inglés. +- `README.es.md` — las mismas instrucciones en español. Está en las 163 carpetas. +- `test.js` — la batería de Jest. No hace falta que la abras. Está en los 162 ejercicios de código. +- Un fichero oculto con la solución. Está en los 162 ejercicios de código, con el nombre `solution.hide.js` en todos salvo en `011-isGreaterThanTen`, donde se llama `solutions.hide.js`. -> 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. +La carpeta `00-Welcome` solo tiene los dos READMEs: es la página de introducción, no un ejercicio. -## Colaboradores - -Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +¿Has encontrado un error o una errata? Abre un issue en [este repositorio](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/issues) — los ejercicios se construyeron entre mucha gente y los avisos se agradecen. -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 🤓 (build-tutorial) ✅ (documentación) 📖 +## 🤝 Colaboradores -2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador), (traducción) 🌎 +El tutorial lo arrancó [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), y estas son las personas con más commits en el repositorio a día de hoy: -3. [Ricardo Rodriguez (RickRodriguez8080)](https://github.com/RickRodriguez8080) contribución: (build-tutorial) ✅, (documentación) 📖 +- [Jose Mora (josemoracard)](https://github.com/josemoracard) — 1.196 commits +- [Tomas Gonzalez (tommygonzaleza)](https://github.com/tommygonzaleza) — 367 commits +- [Martín Suárez (kiddopro)](https://github.com/kiddopro) — 110 commits +- [Elvira Quiroz (ElviraQDP)](https://github.com/ElviraQDP) — 105 commits +- [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr) — 96 commits +- [Ernesto Gonzalez (UmiKami)](https://github.com/UmiKami) — 43 commits +- [Paolo Lucano (plucodev)](https://github.com/plucodev) — 39 commits -Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! +Y [todas las demás personas del gráfico de contribuciones](https://github.com/4GeeksAcademy/master-javascript-programming-exercises/graphs/contributors). Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors) ([leyenda de emojis](https://github.com/kentcdodds/all-contributors#emoji-key)) y cualquier tipo de contribución es bienvenida. -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). +Este tutorial es uno de tantos construidos por estudiantes y profesores de [4Geeks Academy](https://4geeks.com). + From 0e4cca1d71b1867da243f7942bd19d08efbf636e 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:13:10 +0200 Subject: [PATCH 3/4] docs(readme): rewrite for clarity, SEO and AI answer engines From 7dc29976e479999eda7d56b5593cbb16d780d3f7 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:13:11 +0200 Subject: [PATCH 4/4] docs(readme): rewrite for clarity, SEO and AI answer engines