From fd0e1652f7e5223b03a7f518906e50a57328fcdc 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 12:25:17 +0200 Subject: [PATCH 1/2] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.md | 201 +++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 161 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index dd2f56dc..17112298 100644 --- a/README.md +++ b/README.md @@ -1,73 +1,194 @@ -# JavaScript exercises tutorial at 4Geeks Academy - - +
+ +# Javascript Beginner Tutorial (interactive) -> 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/) +[![Certified tutorial by 4Geeks Academy](https://img.shields.io/badge/4Geeks_Academy-Certified_tutorial-2563eb?style=for-the-badge)](https://4geeks.com/interactive-exercise/javascript-beginner-exercises) +[![25 auto-graded exercises with LearnPack](https://img.shields.io/badge/LearnPack-25_auto--graded_exercises-2563eb?style=for-the-badge)](https://github.com/learnpack/learnpack) +[![Open in Codespaces](https://img.shields.io/badge/Open_in-Codespaces-fb5a1f?style=for-the-badge&logo=github)](https://codespaces.new/?repo=4GeeksAcademy/javascript-beginner-exercises-tutorial) -![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-beginner-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) +![Cover of the tutorial: the words Learn Javascript Beginner interactive in black and orange type, next to the yellow hexagonal JS logo](https://raw.githubusercontent.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/HEAD/preview.png) -*Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/master/README.es.md) :es:* +
-Complete selection of auto-graded and interactive JavaScript exercises for anyone interested in learning JavaScript! +This tutorial is a set of **25 auto-graded JavaScript exercises** that take roughly **8 hours** to finish, starting from your first `console.log()` and ending with array and string methods. Every exercise ships an `app.js` you edit, a Jest test file that grades it instantly, and a hidden solution. 15 of them include a video walkthrough, and all 25 are written in English and Spanish. No prior programming experience required. -## Before you start... some related tutorials: -
    -
  1. JavaScript for Beginners ← 🔥 You are here
  2. -
  3. Looping with JavaScript
  4. -
  5. JavaScript Functions
  6. -
  7. Master JavaScript
  8. -
+## 📋 About this tutorial + +- **Difficulty**: easy (beginner, no previous code required) +- **Estimated duration**: 8 hours +- **Exercises**: 25 graded exercises + 1 welcome step +- **Technologies**: JavaScript (ES6), Node.js 22, Jest 29.7.0, LearnPack 5.0.348 +- **Grading**: automatic and `isolated` — each exercise is tested on its own +- **Video solutions**: 15 exercises include a linked video walkthrough +- **Languages**: [English](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/HEAD/README.md) · [Español](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/HEAD/README.es.md) + + +## 🎯 What will you learn? + +The 25 exercises walk through the core of the language, one idea at a time: + +- **Printing and variables**: `console.log()`, declaring variables, and printing their value. +- **Arithmetic**: the `*` operator and storing a result in a variable. +- **User input**: `prompt()` appears in 4 exercises, together with the type conversion it forces on you. +- **Constants**: `const`, why it is read-only, and the exact error you get when you reassign it. +- **Strings**: concatenation, assembling a full HTML document out of 8 constants, and 8 string methods (`length`, `toUpperCase()`, `toLowerCase()`, `indexOf()`, `slice()`, `includes()`, `replace()`, `trim()`). +- **Functions**: calling an existing one, writing your own body, returning values, and passing 3 arguments. +- **Conditionals**: `if...else` with three branches, a 4-tier pricing problem, and a `switch` with 3 cases plus a `default`. +- **Randomness**: `Math.random()` and `Math.floor()` to produce integers in a given range. +- **Loops**: `for`, `while` (including how to stop an infinite one), `for...of`, and FizzBuzz from 1 to 100. +- **Arrays and objects**: index access, `push()`, `pop()`, `shift()`, `unshift()`, `length`, key-value pairs, and dot vs. bracket notation. + +## 👀 What will you build? + +Every numbered folder inside `exercises/` is one small self-contained program you complete and run: + +1. **Hello World** — print `Hello World` with `console.log()`. +2. **Print variables to the console** — declare `color = "red"` and print it. +3. **Multiply two values** — store `2345 * 7323` in `variablesAreCool`. +4. **User inputted variables** — add 10 years to an `age` captured with `prompt()`. +5. **Constants** — fix a crash and make the program output `0.9`. +6. **String concatenation** — set two variables so the output reads `Hello World`. +7. **Creating basic HTML code** — join 8 constants into ``. +8. **Calling your first function** — call `isOdd()` with the number 45345. +9. **Creating your first function** — write the body so the program prints `7`. +10. **Creating a new function** — build `shortIntroduction(name, profession, age)`. +11. **Your first "if" statement** — three answers depending on the kilometres left. +12. **How much does the wedding cost?** — `getPrice()` returning 4000, 10000, 15000 or 20000. +13. **Your first switch statement** — shoe colours `red`, `green` and `blue`, returning `true` or `false`. +14. **Random numbers** — turn `Math.random()` into an integer between 1 and 10. +15. **Random numbers from one to six** — the same idea, this time a dice. +16. **Your first loop** — print the integers 0 to 100. +17. **Creating a `for` loop** — a `standardsMaker()` that writes one phrase 300 times. +18. **The "while" loop** — repair an infinite loop and count down from 100 to 0. +19. **Random colors loop** — hand one of 4 colours to each of 10 students. +20. **Looping with FizzBuzz** — the classic interview exercise, 1 to 100. +21. **Your first array** — a `colors` array printed by index. +22. **Array methods** — `push()`, `shift()` and `length` on a list of students. +23. **Your first object** — a `user` object read with dot notation. +24. **For...of loop** — iterate 5 numbers and print each one doubled. +25. **String methods** — length, case, `indexOf()`, `slice()`, `includes()` and `replace()` on one sentence. + +There is also a `00-Welcome` step with an intro video before exercise 1, so the tutorial has 26 steps in total. + +![Yellow low-poly banner with the message "i love JS", the heart drawn in red, used as the opening image of the tutorial](https://raw.githubusercontent.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/HEAD/.learn/assets/i-love-javascript.jpeg) + +## 🎓 What do you need before starting? + +- **No programming experience.** The difficulty declared in `learn.json` is `easy`, and exercise 1 is a single `console.log()`. +- **A GitHub account** if you take the one-click route: Codespaces opens the whole environment in the browser with nothing installed on your machine. +- **Node.js** only if you want to run it locally. The included dev container is built on the official Node.js 22 image. +- **English or Spanish.** All 26 steps ship a `README.md` and a `README.es.md`. +- **A habit of searching.** Several hints deliberately send you to Google — exercise 5, for instance, tells you to look up `TypeError assignment to constant variable` instead of handing you the fix. + +## ✅ How does the automatic grading work? + +- 25 of the 26 folders contain a test file (24 named `tests.js`, one named `test.js`) executed by **Jest 29.7.0**. +- `learn.json` sets `"grading": "isolated"`, so each exercise is compiled and tested on its own — a broken exercise 12 does not block exercise 13. +- The tests inspect real behaviour, not just text. Exercise 12 loads your `app.js` with `rewire`, extracts `getPrice` and calls it with 50, 51, 100, 101, 200 and 201 to check every boundary of the price table. +- Some tests also count calls. Exercise 1 asserts that `console.log` was called with `Hello World` **and** that it was called exactly once. +- Every exercise carries a `solution.hide.js` you can reveal after trying. + +> 💡 The original authors warn that the grader is very rigid and strict. Read a red test as a suggestion, not as a verdict on your code. + +## 💡 What mistakes should you avoid? + +- **Treating `prompt()` output as a number.** It always returns a string, so `age + 10` on the input `25` gives `2510`, not `35`. Convert it first (exercise 4). +- **Reassigning a `const`.** JavaScript throws `TypeError: Assignment to constant variable` — that is the crash exercise 5 asks you to fix. +- **Ordering the `if...else` branches badly in exercise 12.** The thresholds are exact: 50 guests still cost 4000, but 51 already cost 10000, and 200 cost 15000 while 201 cost 20000. +- **Forgetting to normalise user input in the `switch`.** `Red` will not match `case 'red'`; the hint points you to `toLowerCase()` (exercise 13). +- **Expecting `Math.random()` to give you integers.** It returns a decimal between 0 and 1, 1 excluded. You multiply first and then apply `Math.floor()` (exercises 14, 15, 19). +- **Writing a `while` with no exit.** Exercise 18 hands you a loop that crashes the program until you fix the condition or the increment. +- **Assuming strings change in place.** They are immutable: `replace()` returns a new string, and `indexOf()` returns `-1` when the text is not found (exercise 25). +- **Adding extra `console.log()` lines to debug.** Several tests count how many times the console was called, so leftover prints turn a correct answer red. + +## ❓ Frequently asked questions + +### How long does it take to complete this JavaScript tutorial? + +The declared duration is **8 hours**, which averages a little under 20 minutes per exercise. It is a rough estimate: the first ten exercises are usually a few minutes each, while FizzBuzz (20) and the random colours loop (19) take most people considerably longer. + +### Do I need to know how to program before starting? -> 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. +No. The difficulty is set to `easy` and the first exercise is one line of `console.log()`. Every concept — variables, functions, conditionals, loops, arrays, objects — is introduced in its own README before you are asked to use it. -## One click installation (recommended): +### Do I have to install anything on my computer? -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). +Not if you use the Codespaces button: the environment opens in the browser and starts the exercises for you. If you prefer to work locally you need Node.js and one global install, `npm i @learnpack/learnpack -g`. The dev container pins the versions it uses: LearnPack 5.0.348, the `@learnpack/node` plugin 1.1.15 and Jest 29.7.0. -> 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` +### Are these exercises free, and can I republish them? -## Local Installation +Opening, running and completing them costs nothing, and the code you write in `app.js` is yours. The repository itself is **not open source**: [LICENSE.md](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/HEAD/LICENSE.md) reserves all intellectual property rights and explicitly forbids republishing, selling, sub-licensing, reproducing or redistributing the material. Read it before reusing anything. -[Clone the repository](https://4geeks.com/how-to/github-clone-repository) in your local environment and follow the steps below: +### Does this tutorial cover the DOM, React or the browser APIs? -1. Install LearnPack, the package manager for learning tutorials and the node compiler plugin for learnpack, make sure you also have node.js 16+: +No. Not a single exercise touches `document`, `querySelector` or `addEventListener` — everything runs through the console, and the only browser function used is `prompt()`, in 4 exercises. Exercise 7 does produce HTML, but as a concatenated string, never as elements on a page. + +### Is it still worth learning plain JavaScript first? + +The browser runs JavaScript natively, and React, Vue, Angular and Node.js are all written in it, so loops, conditionals, arrays and objects are the same in every one of them. Learning them without a framework in the way is why this package is 25 console programs and zero build tooling. + +### What should I do after finishing these 25 exercises? + +Move on to the follow-up packages in the same series: [Looping with JavaScript](https://4geeks.com/interactive-exercise/javascript-array-loops-exercises), then [JavaScript Functions](https://4geeks.com/interactive-exercise/javascript-functions-exercises-tutorial), and finally [Master JavaScript](https://4geeks.com/interactive-exercise/master-javascript-exercises). + + +## 📚 Before you start, some related tutorials + +1. [JavaScript for Beginners](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial) ← 🔥 You are here +2. [Looping with JavaScript](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial) +3. [JavaScript Functions](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial) +4. [Master JavaScript](https://github.com/4GeeksAcademy/master-javascript-programming-exercises) + +## 🚀 How to start + +The fastest way is one click: [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). + +Once VSCode opens, the LearnPack exercises should start automatically. 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 + +[Clone the repository](https://4geeks.com/how-to/github-clone-repository) into your local environment and then: + +1. Install [LearnPack](https://github.com/learnpack/learnpack), the package manager for interactive tutorials, together with the node compiler plugin. You need [Node.js](https://nodejs.org/) 16 or newer: ```bash -$ learnpack start +$ npm i @learnpack/learnpack -g +$ learnpack plugins:install @learnpack/node ``` - -> 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. +2. Start the exercises by running this command at the same level as your `learn.json` file: -## How are the exercises organized? +```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 small standalone JavaScript program made of these files: -## Contributors +- **`app.js`**: the entry file you edit and the computer executes. +- **`README.md`** and **`README.es.md`**: the instructions, in English and Spanish. +- **`tests.js`**: the [Jest](https://jestjs.io/) script that grades your answer. You do not need to open it. +- **`solution.hide.js`**: one possible solution, hidden until you ask for it. -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](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/issues) — these exercises are maintained with the help of contributors like you. -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) 🌎 +Thanks goes to these wonderful people: -3. [Ricardo Rodriguez (RickRodriguez8080)](https://github.com/RickRodriguez8080) contribution: (build-tutorial) ✅, (documentation) 📖 +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. Ricardo Rodriguez (RickRodriguez8080) — build-tutorial ✅, documentation 📖 -This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! +See the full list on the [contributors graph](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/graphs/contributors). This project follows the all-contributors specification, 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 and many other exercises are built by students and instructors at [4Geeks Academy](https://4geeks.com) as part of its coding bootcamp. + From a640284a22fb1aada6f26ccfafdc39886c741149 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 12:25:19 +0200 Subject: [PATCH 2/2] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.es.md | 202 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 162 insertions(+), 40 deletions(-) diff --git a/README.es.md b/README.es.md index 0e41079b..eb23875f 100644 --- a/README.es.md +++ b/README.es.md @@ -1,72 +1,194 @@ -# Tutorial de ejercicios de JavaScript para Principiantes en 4Geeks Academy - - +
+ +# Tutorial para Principiantes de Javascript (Interactivo) + +[![Tutorial certificado por 4Geeks Academy](https://img.shields.io/badge/4Geeks_Academy-Tutorial_certificado-2563eb?style=for-the-badge)](https://4geeks.com/es/interactive-exercise/ejercicios-javascript-para-principiantes) +[![25 ejercicios autocorregidos con LearnPack](https://img.shields.io/badge/LearnPack-25_ejercicios_autocorregidos-2563eb?style=for-the-badge)](https://github.com/learnpack/learnpack) +[![Abrir en Codespaces](https://img.shields.io/badge/Abrir_en-Codespaces-fb5a1f?style=for-the-badge&logo=github)](https://codespaces.new/?repo=4GeeksAcademy/javascript-beginner-exercises-tutorial) -> 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/) +![Portada del tutorial: el texto Learn Javascript Beginner interactive en tipografía negra y naranja, junto al logo hexagonal amarillo de JS](https://raw.githubusercontent.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/HEAD/preview.png) -![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-beginner-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) +
-¡Selección completa de ejercicios de JavaScript interactivos autograduados para cualquier persona interesada en aprender JavaScript! +Este tutorial reúne **25 ejercicios de JavaScript con corrección automática** que se completan en unas **8 horas**, desde tu primer `console.log()` hasta los métodos de arrays y strings. Cada ejercicio trae un `app.js` que editas, un fichero de tests con Jest que lo corrige al instante y una solución oculta. 15 incluyen vídeo explicativo y los 25 están escritos en español y en inglés. No hace falta saber programar. + + +## 📋 Ficha del tutorial + +- **Dificultad**: fácil (nivel principiante, sin conocimientos previos) +- **Duración estimada**: 8 horas +- **Ejercicios**: 25 ejercicios corregidos + 1 paso de bienvenida +- **Tecnologías**: JavaScript (ES6), Node.js 22, Jest 29.7.0, LearnPack 5.0.348 +- **Corrección**: automática y `isolated` — cada ejercicio se evalúa por separado +- **Vídeos de solución**: 15 ejercicios enlazan un vídeo explicativo +- **Idiomas**: [English](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/HEAD/README.md) · [Español](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/HEAD/README.es.md) + + +## 🎯 ¿Qué vas a aprender? + +Los 25 ejercicios recorren el núcleo del lenguaje, una idea cada vez: + +- **Imprimir y declarar variables**: `console.log()`, declarar una variable y sacar su valor por consola. +- **Aritmética**: el operador `*` y cómo guardar el resultado en una variable. +- **Entrada del usuario**: `prompt()` aparece en 4 ejercicios, junto con la conversión de tipos que obliga a hacer. +- **Constantes**: `const`, por qué es de solo lectura y qué error exacto salta al reasignarla. +- **Strings**: concatenación, montar un documento HTML completo a partir de 8 constantes y 8 métodos de texto (`length`, `toUpperCase()`, `toLowerCase()`, `indexOf()`, `slice()`, `includes()`, `replace()`, `trim()`). +- **Funciones**: llamar a una que ya existe, escribir tú el cuerpo, devolver valores y pasar 3 argumentos. +- **Condicionales**: `if...else` de tres ramas, un problema de precios con 4 tramos y un `switch` con 3 casos más su `default`. +- **Azar**: `Math.random()` y `Math.floor()` para obtener enteros dentro de un rango. +- **Bucles**: `for`, `while` (incluido cómo frenar uno infinito), `for...of` y el FizzBuzz del 1 al 100. +- **Arrays y objetos**: acceso por índice, `push()`, `pop()`, `shift()`, `unshift()`, `length`, pares clave-valor y notación de punto frente a corchetes. + +## 👀 ¿Qué vas a construir? + +Cada carpeta numerada dentro de `exercises/` es un programa pequeño e independiente que completas y ejecutas: + +1. **Hello World** — imprimir `Hello World` con `console.log()`. +2. **Imprimir variables en la consola** — declarar `color = "red"` y mostrarlo. +3. **Multiplicar dos valores** — guardar `2345 * 7323` en `variablesAreCool`. +4. **Variables introducidas por el usuario** — sumar 10 años a una `age` capturada con `prompt()`. +5. **Constantes** — arreglar el error que revienta el programa y conseguir que imprima `0.9`. +6. **Concatenación de strings** — ajustar dos variables para que la salida diga `Hello World`. +7. **Crear un HTML básico** — unir 8 constantes hasta formar ``. +8. **Llamar a tu primera función** — invocar `isOdd()` pasándole el número 45345. +9. **Crear tu primera función** — escribir el cuerpo para que el programa imprima `7`. +10. **Crear una función nueva** — construir `shortIntroduction(name, profession, age)`. +11. **Tu primer `if`** — tres respuestas distintas según los kilómetros que queden. +12. **Cuánto cuesta la boda** — una función `getPrice()` que devuelve 4000, 10000, 15000 o 20000. +13. **Tu primer `switch`** — colores de zapato `red`, `green` y `blue`, devolviendo `true` o `false`. +14. **Números aleatorios** — convertir `Math.random()` en un entero del 1 al 10. +15. **Aleatorios del uno al seis** — la misma idea, ahora como un dado. +16. **Tu primer bucle** — imprimir los enteros del 0 al 100. +17. **Crear un bucle `for`** — un `standardsMaker()` que escribe una frase 300 veces. +18. **Bucle `while`** — reparar un bucle infinito y contar hacia atrás del 100 al 0. +19. **Bucle de colores aleatorios** — repartir uno de 4 colores a cada uno de 10 alumnos. +20. **FizzBuzz con bucles** — el clásico de las entrevistas técnicas, del 1 al 100. +21. **Tu primer array** — un array `colors` impreso por índice. +22. **Métodos de array** — `push()`, `shift()` y `length` sobre una lista de estudiantes. +23. **Tu primer objeto** — un objeto `user` leído con notación de punto. +24. **Bucle `for...of`** — recorrer 5 números e imprimir cada uno multiplicado por 2. +25. **Métodos de string** — longitud, mayúsculas, `indexOf()`, `slice()`, `includes()` y `replace()` sobre una frase. + +Antes del ejercicio 1 hay además un paso `00-Welcome` con vídeo de introducción, así que el tutorial suma 26 pasos en total. + +![Banner amarillo de polígonos con el mensaje "i love JS" y el corazón dibujado en rojo, la imagen de apertura del tutorial](https://raw.githubusercontent.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/HEAD/.learn/assets/i-love-javascript.jpeg) + +## 🎓 ¿Qué necesitas antes de empezar? + +- **Ninguna experiencia programando.** La dificultad declarada en `learn.json` es `easy` y el primer ejercicio es un único `console.log()`. +- **Una cuenta de GitHub** si eliges la vía rápida: Codespaces abre el entorno completo en el navegador sin instalar nada en tu ordenador. +- **Node.js** solo si prefieres trabajar en local. El contenedor de desarrollo incluido parte de la imagen oficial de Node.js 22. +- **Español o inglés.** Los 26 pasos traen su `README.md` y su `README.es.md`. +- **Costumbre de buscar.** Varias pistas te mandan a Google a propósito: el ejercicio 5, por ejemplo, te pide buscar `TypeError assignment to constant variable` en vez de darte la solución. + +## ✅ ¿Cómo funciona la corrección automática? + +- 25 de las 26 carpetas contienen un fichero de tests (24 se llaman `tests.js` y uno `test.js`) que ejecuta **Jest 29.7.0**. +- En `learn.json` la corrección es `"grading": "isolated"`, así que cada ejercicio se compila y se evalúa por su cuenta: si el 12 está roto, el 13 sigue funcionando. +- Los tests miran comportamiento real, no texto. El ejercicio 12 carga tu `app.js` con `rewire`, extrae `getPrice` y lo llama con 50, 51, 100, 101, 200 y 201 para comprobar todos los límites de la tabla de precios. +- Algunos tests además cuentan llamadas: el ejercicio 1 exige que `console.log` se haya llamado con `Hello World` **y** que se haya llamado una sola vez. +- Cada ejercicio incluye un `solution.hide.js` que puedes destapar después de intentarlo. + +> 💡 Los autores avisan de que el corrector es muy rígido y estricto. Toma un test en rojo como una sugerencia, no como una sentencia sobre tu código. + +## 💡 ¿Qué errores conviene evitar? + +- **Tratar lo que devuelve `prompt()` como un número.** Siempre devuelve texto, así que con la entrada `25` la operación `age + 10` da `2510` y no `35`. Hay que convertirlo antes (ejercicio 4). +- **Reasignar una `const`.** JavaScript lanza `TypeError: Assignment to constant variable`, que es justo el fallo que el ejercicio 5 te pide arreglar. +- **Ordenar mal las ramas del `if...else` del ejercicio 12.** Los umbrales son exactos: 50 invitados todavía cuestan 4000, pero 51 ya cuestan 10000, y 200 cuestan 15000 mientras que 201 cuestan 20000. +- **Olvidar normalizar la entrada en el `switch`.** `Red` no coincide con `case 'red'`; la pista del ejercicio 13 te lleva a `toLowerCase()`. +- **Esperar que `Math.random()` devuelva enteros.** Devuelve un decimal entre 0 y 1, sin incluir el 1. Primero se multiplica y luego se aplica `Math.floor()` (ejercicios 14, 15 y 19). +- **Escribir un `while` sin salida.** El ejercicio 18 te entrega un bucle que tumba el programa hasta que corrijas la condición o el incremento. +- **Dar por hecho que los strings se modifican.** Son inmutables: `replace()` devuelve un string nuevo e `indexOf()` devuelve `-1` cuando no encuentra el texto (ejercicio 25). +- **Dejar `console.log()` de depuración.** Varios tests cuentan cuántas veces se llamó a la consola, así que un print olvidado pone en rojo una respuesta correcta. + +## ❓ Preguntas frecuentes + +### ¿Cuánto se tarda en completar este tutorial de JavaScript? + +La duración declarada es de **8 horas**, algo menos de 20 minutos de media por ejercicio. Es una estimación aproximada: los diez primeros suelen salir en pocos minutos, mientras que el FizzBuzz (20) y el bucle de colores aleatorios (19) le llevan bastante más tiempo a casi todo el mundo. + +### ¿Necesito saber programar antes de empezar? + +No. La dificultad está marcada como `easy` y el primer ejercicio es una línea de `console.log()`. Cada concepto —variables, funciones, condicionales, bucles, arrays y objetos— se explica en su propio README antes de pedirte que lo uses. + +### ¿Tengo que instalar algo en mi ordenador? + +No, si usas el botón de Codespaces: el entorno se abre en el navegador y arranca los ejercicios solo. Si prefieres trabajar en local necesitas Node.js y una instalación global, `npm i @learnpack/learnpack -g`. El contenedor de desarrollo fija las versiones que utiliza: LearnPack 5.0.348, el plugin `@learnpack/node` 1.1.15 y Jest 29.7.0. + +### ¿Son gratis estos ejercicios? ¿Puedo republicarlos? + +Abrirlos, ejecutarlos y completarlos no cuesta nada, y el código que escribas en `app.js` es tuyo. El repositorio en sí **no es open source**: el fichero [LICENSE.md](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/blob/HEAD/LICENSE.md) se reserva todos los derechos de propiedad intelectual y prohíbe expresamente republicar, vender, sublicenciar, reproducir o redistribuir el material. Léelo antes de reutilizar nada. + +### ¿Se ve el DOM, React o las APIs del navegador? + +No. Ningún ejercicio toca `document`, `querySelector` ni `addEventListener`: todo sucede en la consola y la única función del navegador que se usa es `prompt()`, en 4 ejercicios. El ejercicio 7 sí genera HTML, pero como string concatenado, nunca como elementos pintados en una página. + +### ¿Sigue mereciendo la pena aprender JavaScript "a pelo"? + +El navegador ejecuta JavaScript de forma nativa, y React, Vue, Angular y Node.js están escritos en él, así que los bucles, los condicionales, los arrays y los objetos son idénticos en todos. Aprenderlos sin un framework por medio es la razón de que este paquete sean 25 programas de consola y cero herramientas de build. + +### ¿Qué hago después de terminar los 25 ejercicios? + +Continuar con los siguientes paquetes de la serie: [Looping con JavaScript](https://4geeks.com/es/interactive-exercise/javascript-array-loops-exercises-es), después [Funciones de JavaScript](https://4geeks.com/es/interactive-exercise/javascript-functions-exercises-tutorial-es) y por último [Master JavaScript](https://4geeks.com/es/interactive-exercise/master-javascript-exercises-es). -## Antes de empezar... algunos tutoriales relacionados -
    -
  1. JavaScript para Principiantes ← 🔥 Estás aquí
  2. -
  3. Looping con JavaScript
  4. -
  5. Funciones de JavaScript
  6. -
  7. Master JavaScript
  8. -
+## 📚 Antes de empezar, algunos tutoriales relacionados -> ¡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. +1. [JavaScript para Principiantes](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial) ← 🔥 Estás aquí +2. [Looping con JavaScript](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial) +3. [Funciones de JavaScript](https://github.com/4GeeksAcademy/javascript-functions-exercises-tutorial) +4. [Master JavaScript](https://github.com/4GeeksAcademy/master-javascript-programming-exercises) -## Instalación en un clic (recomendado) +## 🚀 Cómo empezar -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). +Lo más rápido es un clic: [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). -> 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` +Cuando VSCode se abra, los ejercicios de LearnPack deberían arrancar automáticamente. Si no lo hacen, escribe esto en la terminal: -## Instalación local: +```bash +$ learnpack start +``` -Clona el repositorio en tu ambiente local y sigue los siguientes pasos: +## 💻 Instalación local -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: +[Clona el repositorio](https://4geeks.com/how-to/github-clone-repository) en tu entorno local y después: + +1. Instala [LearnPack](https://github.com/learnpack/learnpack), el gestor de paquetes de los tutoriales interactivos, junto con el plugin compilador de node. Necesitas [Node.js](https://nodejs.org/) 16 o superior: ```bash $ npm i @learnpack/learnpack -g +$ learnpack plugins:install @learnpack/node ``` -2. Inicializa el tutorial/ejercicios ejecutando el siguiente comando en el mismo nivel donde se encuentra su archivo learn.json: +2. Arranca los ejercicios ejecutando este comando al mismo nivel que tu fichero `learn.json`: ```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. +## 📝 Cómo están organizados los ejercicios -## ¿Cómo están organizados los ejercicios? +Cada ejercicio es un programa de JavaScript pequeño e independiente formado por estos ficheros: -Cada ejercicio es una pequeña aplicación de React que contiene los siguientes archivos: +- **`app.js`**: el fichero de entrada que editas y que ejecuta el ordenador. +- **`README.md`** y **`README.es.md`**: las instrucciones, en inglés y en español. +- **`tests.js`**: el script de [Jest](https://jestjs.io/) que corrige tu respuesta. No necesitas abrirlo. +- **`solution.hide.js`**: una solución posible, oculta hasta que la pidas. -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). +¿Has encontrado un bug o una errata? [Abre un issue](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/issues) — estos ejercicios se mantienen con la ayuda de colaboradores como tú. -## Colaboradores - -Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +## 🤝 Colaboradores -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 🤓 (build-tutorial) ✅ (documentación) 📖 +Gracias a estas personas: -2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador), (traducción) 🌎 +1. [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr) — programador 💻, idea 🤔, build-tests ⚠️, revisión de pull requests 👀, build-tutorial ✅, documentación 📖 +2. [Paolo (plucodev)](https://github.com/plucodev) — reporte de bugs 🐛, programador 💻, traducción 🌎 +3. Ricardo Rodriguez (RickRodriguez8080) — build-tutorial ✅, documentación 📖 -3. [Ricardo Rodriguez (RickRodriguez8080)](https://github.com/RickRodriguez8080) contribución: (build-tutorial) ✅, (documentación) 📖 +Puedes ver la lista completa en el [gráfico de colaboradores](https://github.com/4GeeksAcademy/javascript-beginner-exercises-tutorial/graphs/contributors). Este proyecto sigue la especificación all-contributors y todas las contribuciones son bienvenidas. -Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! - -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). +Este y otros muchos ejercicios los construyen estudiantes e instructores de [4Geeks Academy](https://4geeks.com) dentro de su bootcamp de programación. +