From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../building_blocks/bucle_codigo/index.html | 923 +++++++++++++++++++++ .../building_blocks/conditionals/index.html | 778 +++++++++++++++++ .../construyendo_tu_propia_funcion/index.html | 252 ++++++ .../javascript/building_blocks/eventos/index.html | 578 +++++++++++++ .../building_blocks/functions/index.html | 400 +++++++++ .../building_blocks/galeria_de_imagenes/index.html | 144 ++++ .../es/learn/javascript/building_blocks/index.html | 71 ++ .../building_blocks/return_values/index.html | 168 ++++ 8 files changed, 3314 insertions(+) create mode 100644 files/es/learn/javascript/building_blocks/bucle_codigo/index.html create mode 100644 files/es/learn/javascript/building_blocks/conditionals/index.html create mode 100644 files/es/learn/javascript/building_blocks/construyendo_tu_propia_funcion/index.html create mode 100644 files/es/learn/javascript/building_blocks/eventos/index.html create mode 100644 files/es/learn/javascript/building_blocks/functions/index.html create mode 100644 files/es/learn/javascript/building_blocks/galeria_de_imagenes/index.html create mode 100644 files/es/learn/javascript/building_blocks/index.html create mode 100644 files/es/learn/javascript/building_blocks/return_values/index.html (limited to 'files/es/learn/javascript/building_blocks') diff --git a/files/es/learn/javascript/building_blocks/bucle_codigo/index.html b/files/es/learn/javascript/building_blocks/bucle_codigo/index.html new file mode 100644 index 0000000000..e26509afc5 --- /dev/null +++ b/files/es/learn/javascript/building_blocks/bucle_codigo/index.html @@ -0,0 +1,923 @@ +--- +title: Bucles +slug: Learn/JavaScript/Building_blocks/Bucle_codigo +translation_of: Learn/JavaScript/Building_blocks/Looping_code +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}
+ +

Los lenguajes de programación son muy útiles para completar rápidamente tareas repetitivas, desde múltimples cálculos básicos hasta cualquier otra situación en donde tengas un montón de elementos de trabajo similares que completar. Aquí vamos a ver las estructuras de bucles disponibles en JavaScript que pueden manejar tales necesidades.

+ + + + + + + + + + + + +
Prerequisitos:Conocimientos básicos de computación, entendimiento básico de HTML y CSS, JavaScript first steps.
Objetivo:Entender cómo usar bucles en JavaScript.
+ +

Mantente en el Bucle

+ +

Bucles, bucles, bucles. Además de ser conocidos como un cereal de desayuno popular, montañas rusas y producción músical, también son un concepto muy importante en programación. Los bucles de programación están relacionados con todo lo referente a hacer una misma cosa una y otra vez — que se denomina como iteración en el idioma de programación.

+ +

Consideremos el caso de un agricultor que se asegura de tener suficiente comida para alimentar a su familia durante la semana. Podría usar el siguiente bucle para lograr esto:

+ +


+

+ +

Un bucle cuenta con una o más de las siguientes características:

+ + + +

En {{glossary("pseudocódigo")}},esto se vería como sigue:

+ +
bucle(comida = 0; comidaNecesaria = 10) {
+  if (comida = comidaNecesaria) {
+    salida bucle;
+    // Tenemos suficiente comida; vamonos para casa
+  } else {
+    comida += 2; // Pasar una hora recogiendo 2 más de comida
+    // Comenzar el bucle de nuevo
+  }
+}
+ +

Así que la cantidad necesaria de comida se establece en 10, y la cantidad incial del granjero en 0. En cada iteración del bucle comprobamos si la cantidad de comida del granjero es mayor o igual a la cantidad que necesita. Si lo es, podemos salir del bucle. Si no, el granjero se pasará una hora más recogiendo dos porciones de comida, y el bucle arrancará de nuevo.

+ +

¿Por qué molestarse?

+ +

En este punto, probablemente entiendas los conceptos de alto nivel que hay detrás de los bucles, pero probablemente estés pensando "OK, fantástico, pero ¿cómo me ayuda esto a escribir un mejor codigo JavaScript?". Como dijimos antes, los bucles tienen que ver con hacer lo mismo una y otra vez, lo cual es bueno para completar rápidamente tareas repetitivas.

+ +

Muchas veces, el código será ligeramente diferente en cada iteracción sucesiva del bucle, lo que significa que puedes completar una carga completa de tareas que son similares, pero ligeramente diferentes — si tienes muchos calculos diferentes que hacer, quieres hacer cada uno de ellos, ¡no el mismo una y otra vez!

+ +

Vamos a ver un ejemplo para ilustrar perfectamente por qué los bucles son tan útiles. Digamos que queremos dibujar 100 círculos aleatorios en un elemento {{htmlelement("canvas")}} (presiona el botón Update para ejecutar el ejemplo una y otra vez y ver diferentes configuraciones aleatorias):

+ + + +

{{ EmbedLiveSample('Hidden_code', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

+ +

No tienes que entender todo el código por ahora, pero vamos a echar un vistazo a la parte de código que dibuja los 100 círculos:

+ +
for (var i = 0; i < 100; i++) {
+  ctx.beginPath();
+  ctx.fillStyle = 'rgba(255,0,0,0.5)';
+  ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+  ctx.fill();
+}
+ +

Debes quedarte con la idea básica.  — utilizamos un bucle para ejecutar 100 iteracciones de este código, cada una de las cuales dibuja un círculo en una posición aleatoria de la página. La cantidad de código necesario sería el mismo si dibujáramos 100, 1000, o 10,000 círculos. Solo necesitamos cambiar un número.

+ +

Si no usáramos un bucle aquí, tendríamos que repetir el siguiente código por cada círculo que quisiéramos dibujar:

+ +
ctx.beginPath();
+ctx.fillStyle = 'rgba(255,0,0,0.5)';
+ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ctx.fill();
+ +

Esto sería muy aburrido y difícil de mantener de forma rápida. Los bucles son realmente lo mejor.

+ +

El bucle estándar for

+ +

Exploremos algunos constructores de bucles específicos. El primero, que usarás la mayoría de las veces, es el bucle for - este tiene la siguiente sintaxis:

+ +
for (inicializador; condición de salida; expresión final) {
+  // código a ejecutar
+}
+ +

Aquí tenemos:

+ +
    +
  1. La palabra reservada for, seguida por algunos paréntesis.
  2. +
  3. Dentro de los paréntesis tenemos tres ítems, separados por punto y coma (;): +
      +
    1. Un inicializador - Este es usualmente una variable con un número asignado, que aumenta el número de veces que el bucle ha sijo ejecutado. También se le llama contador o variable de conteo.
    2. +
    3. Una condición de salida - como se mencionó previamente, ésta define cuando el bucle debería detenerse. Generalmente es una expresión que contiene un operador de comparación, una prueba para verificar ue la condición de término o salida ha sido cumplida.
    4. +
    5. Una expresión final - que es siempre evaluada o ejecutada cada vez que el bucle ha completado una iteración. Usualmente sirve para modificar al contador (incrementando su valor o algunas veces disminuyendolo), para aproximarse a la condición de salida.
    6. +
    +
  4. +
  5. Algunos corchetes curvos que contienen un bloque de código - este código se ejecutará cada vez que se repita el bucle.
  6. +
+ +

Observa un ejemplo real para poder entender esto más claramente.

+ +
var cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
+var info = 'My cats are called ';
+var para = document.querySelector('p');
+
+for (var i = 0; i < cats.length; i++) {
+  info += cats[i] + ', ';
+}
+
+para.textContent = info;
+ +

Esto nos da el siguiente resultado:

+ + + +

{{ EmbedLiveSample('Hidden_code_2', '100%', 60, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Nota: Puedes encontrar este ejemplo de código en GitHub también (además puedes verlo ejecutar en vivo).

+
+ +

Esto muestra un bucle siendo usado para iterar sobre los elementos de un arreglo (matriz), y hacer algo con cada uno de ellos - un patrón muy común en JavaScript. Aquí:

+ +
    +
  1. El iterador, i, inicia en 0 (var i = 0).
  2. +
  3. Se le ha dicho que debe ejecutarse hasta que no sea menor que la longitud del arreglo cats. Esto es importante  - la condición de salida muestra la condicion bajo la cual el bucle seguirá iterando. Así, en este caso, mientras i < cats.length sea verdadero, el bucle seguirá ejecutándose.
  4. +
  5. Dentro del bucle, concatenamos el elemento del bucle actual (cats[i] es cats[lo que sea i en ese momento]) junto con una coma y un espacio, al final de la variable info. Así: +
      +
    1. Durante la primera ejecución,  i = 0, así cats[0] + ', ' se concatenará con la información ("Bill, ").
    2. +
    3. Durante la segunda ejecución, i = 1, así cats[1] + ', ' agregará el siguiente nombre ("Jeff, ").
    4. +
    5. Y así sucesivamente. Después de cada vez que se ejecute el bucle, se incrementará en 1 el valod de i (i++), entonces el proceso comenzará de nuevo.
    6. +
    +
  6. +
  7. Cuando i sea igual a cats.length, el bucle se detendrá, y el navegador se moverá al siguiente segmento de código bajo el bucle.
  8. +
+ +
+

Nota: Hemos programado la condición de salidad como i < cats.length, y no como i <= cats.length, porque los computadores cuentan desde 0, no 1 - inicializamos la variable i en 0, para llegar a i = 4 (el índice del último elemento del arreglo). cats.length responde 5, ya que existen 5 elementos en el arreglo, pero no queremos que i = 5, dado que respondería undefined para el último elemento (no existe un elemento en el arreglo con un índice 5). for the last item (there is no array item with an index of 5). Por ello, queremos llegar a 1 menos que cats.length (i <), que no es lo mismo que cats.length (i <=).

+
+ +
+

Nota: Un error común con la condición de salida es utilizar el comparador "igual a" (===) en vez de "menor o igual a" (<=). Si queremos que nuestro bucle se ejecute hasta que  i = 5, la condición de salida debería ser i <= cats.length. Si la declaramos i === cats.length, el bucle no debería ejecutarse , porque i no es igual a 5 en la primera iteración del bucle, por lo que debería detenerse inmediatamente.

+
+ +

Un pequeño problema que se presenta es que la frase de salida final no está muy bien formada:

+ +
+

My cats are called Bill, Jeff, Pete, Biggles, Jasmin,

+
+ +

Idealmente querríamos cambiar la concatenacion al final de la última iteracion del bucle, así no tendríamos una coma en el final de la frase. Bueno, no hay problema - podemos insertar un condicional dentro de nuestro bucle para solucionar este caso especial:

+ +
for (var i = 0; i < cats.length; i++) {
+  if (i === cats.length - 1) {
+    info += 'and ' + cats[i] + '.';
+  } else {
+    info += cats[i] + ', ';
+  }
+}
+ +
+

Note: You can find this example code on GitHub too (also see it running live).

+
+ +
+

Importante: Con for - como con todos los bucles - debes estar seguro de que el inicializador es repetido hasta que eventualemtne alcance la condición de salida. Si no, el bucle seguirá repitiéndose indefinidamente, y puede que el navegador lo fuerce a detenerse o se interrumpa. Esto se denomina bucle infinito.

+
+ +

Salir de un bucle con break

+ +

Si deseas salir de un bucle antes de que se hayan completado todas las iteraciones, puedes usar la declaración break. Ya la vimos en el artículo previo cuando revisamos la declaración switch - cuando un caso en una declaración switch coincide con la expresión de entrada, la declaración break inmediatamente sale de la declaración switch y avanza al código que se encuentra después.

+ +

Ocurre lo mismo con los bucles - una declaración break saldrá inmediatamente del bucle y hará que el navegador siga con el código que sigue después.

+ +

Digamos que queremos buscar a través de un arreglo de contactos y números telefónicos y retornar sólo el número que queríamos encontrar. primero, un simple HTML -  un {{htmlelement("input")}} de texto que nos permita ingresar un nombre para buscar, un elemento {{htmlelement("button")}} para enviar la búsqueda, y un elemento {{htmlelement("p")}} para mostrar el resultado:

+ +
<label for="search">Search by contact name: </label>
+<input id="search" type="text">
+<button>Search</button>
+
+<p></p>
+ +

Ahora en el JavaScript:

+ +
var contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
+var para = document.querySelector('p');
+var input = document.querySelector('input');
+var btn = document.querySelector('button');
+
+btn.addEventListener('click', function() {
+  var searchName = input.value;
+  input.value = '';
+  input.focus();
+  for (var i = 0; i < contacts.length; i++) {
+    var splitContact = contacts[i].split(':');
+    if (splitContact[0] === searchName) {
+      para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
+      break;
+    } else {
+      para.textContent = 'Contact not found.';
+    }
+  }
+});
+ + + +

{{ EmbedLiveSample('Hidden_code_3', '100%', 100, "", "", "hide-codepen-jsfiddle") }}

+ +
    +
  1. First of all we have some variable definitions — we have an array of contact information, with each item being a string containing a name and phone number separated by a colon.
  2. +
  3. Next, we attach an event listener to the button (btn), so that when it is pressed, some code is run to perform the search and return the results.
  4. +
  5. We store the value entered into the text input in a variable called searchName, before then emptying the text input and focusing it again, ready for the next search.
  6. +
  7. Now onto the interesting part, the for loop: +
      +
    1. We start the counter at 0, run the loop until the counter is no longer less than contacts.length, and increment i by 1 after each iteration of the loop.
    2. +
    3. Inside the loop we first split the current contact (contacts[i]) at the colon character, and store the resulting two values in an array called splitContact.
    4. +
    5. We then use a conditional statement to test whether splitContact[0] (the contact's name) is equal to the inputted searchName. If it is, we enter a string into the paragraph to report what the contact's number is, and use break to end the loop.
    6. +
    +
  8. +
  9. If the contact name does not match the entered search, the paragraph text is set to "Contact not found.", and the loop continues iterating.
  10. +
+ +
+

Note: You can view the full source code on GitHub too (also see it running live).

+
+ +

Skipping iterations with continue

+ +

The continue statement works in a similar manner to break, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop. Let's look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).

+ +

The HTML is basically the same as the last example — a simple text input, and a paragraph for output. The JavaScript is mostly the same too, although the loop itself is a bit different:

+ +
var num = input.value;
+
+for (var i = 1; i <= num; i++) {
+  var sqRoot = Math.sqrt(i);
+  if (Math.floor(sqRoot) !== sqRoot) {
+    continue;
+  }
+
+  para.textContent += i + ' ';
+}
+ +

Here's the output:

+ + + +

{{ EmbedLiveSample('Hidden_code_4', '100%', 100, "", "", "hide-codepen-jsfiddle") }}

+ +
    +
  1. In this case, the input should be a number (num). The for loop is given a counter starting at 1 (as we are not interested in 0 in this case), an exit condition that says the loop will stop when the counter becomes bigger than the input num, and an iterator that adds 1 to the counter each time.
  2. +
  3. Inside the loop, we find the square root of each number using Math.sqrt(i), then check whether the square root is an integer by testing whether it is the same as itself when it has been rounded down to the nearest integer (this is what Math.floor() does to the number it is passed).
  4. +
  5. If the square root and the rounded down square root do not equal one another (!==), it means that the square root is not an integer, so we are not interested in it. In such a case, we use the continue statement to skip on to the next loop iteration without recording the number anywhere.
  6. +
  7. If the square root IS an integer, we skip past the if block entirely so the continue statement is not executed; instead, we concatenate the current i value plus a space on to the end of the paragraph content.
  8. +
+ +
+

Note: You can view the full source code on GitHub too (also see it running live).

+
+ +

while and do ... while

+ +

for is not the only type of loop available in JavaScript. There are actually many others and, while you don't need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognize the same features at work in a slightly different way.

+ +

First, let's have a look at the while loop. This loop's syntax looks like so:

+ +
initializer
+while (exit-condition) {
+  // code to run
+
+  final-expression
+}
+ +

This works in a very similar way to the for loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run — rather than these two items being included inside the parentheses. The exit-condition is included inside the parentheses, which are preceded by the while keyword rather than for.

+ +

The same three items are still present, and they are still defined in the same order as they are in the for loop — this makes sense, as you still have to have an initializer defined before you can check whether it has reached the exit-condition; the final-condition is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the exit-condition has still not been reached.

+ +

Let's have a look again at our cats list example, but rewritten to use a while loop:

+ +
var i = 0;
+
+while (i < cats.length) {
+  if (i === cats.length - 1) {
+    info += 'and ' + cats[i] + '.';
+  } else {
+    info += cats[i] + ', ';
+  }
+
+  i++;
+}
+ +
+

Note: This still works just the same as expected — have a look at it running live on GitHub (also view the full source code).

+
+ +

The do...while loop is very similar, but provides a variation on the while structure:

+ +
initializer
+do {
+  // code to run
+
+  final-expression
+} while (exit-condition)
+ +

In this case, the initializer again comes first, before the loop starts. The do keyword directly precedes the curly braces containing the code to run and the final-expression.

+ +

The differentiator here is that the exit-condition comes after everything else, wrapped in parentheses and preceded by a while keyword. In a do...while loop, the code inside the curly braces is always run once before the check is made to see if it should be executed again (in while and for, the check comes first, so the code might never be executed).

+ +

Let's rewrite our cat listing example again to use a do...while loop:

+ +
var i = 0;
+
+do {
+  if (i === cats.length - 1) {
+    info += 'and ' + cats[i] + '.';
+  } else {
+    info += cats[i] + ', ';
+  }
+
+  i++;
+} while (i < cats.length);
+ +
+

Note: Again, this works just the same as expected — have a look at it running live on GitHub (also view the full source code).

+
+ +
+

Important: With while and do...while — as with all loops — you must make sure that the initializer is iterated so that it eventually reaches the exit condition. If not, the loop will go on forever, and either the browser will force it to stop, or it will crash. This is called an infinite loop.

+
+ +

Active learning: Launch countdown!

+ +

In this exercise, we want you to print out a simple launch countdown to the output box, from 10 down to Blast off. Specifically, we want you to:

+ + + +

If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.

+ + + +

{{ EmbedLiveSample('Active_learning', '100%', 880, "", "", "hide-codepen-jsfiddle") }}

+ +

Active learning: Filling in a guest list

+ +

In this exercise, we want you to take a list of names stored in an array, and put them into a guest list. But it's not quite that easy — we don't want to let Phil and Lola in because they are greedy and rude, and always eat all the food! We have two lists, one for guests to admit, and one for guests to refuse.

+ +

Specifically, we want you to:

+ + + +

We've already provided you with:

+ + + +

Extra bonus question — after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy — there will be a comma at the end of each one. Can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end? Have a look at the Useful string methods article for help.

+ +

If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.

+ + + +

{{ EmbedLiveSample('Active_learning_2', '100%', 680, "", "", "hide-codepen-jsfiddle") }}

+ +

Which loop type should you use?

+ +

For basic uses, for, while, and do...while loops are largely interchangeable. They can all be used to solve the same problems, and which one you use will largely depend on your personal preference — which one you find easiest to remember or most intuitive. Let's have a look at them again.

+ +

First for:

+ +
for (initializer; exit-condition; final-expression) {
+  // code to run
+}
+ +

while:

+ +
initializer
+while (exit-condition) {
+  // code to run
+
+  final-expression
+}
+ +

and finally do...while:

+ +
initializer
+do {
+  // code to run
+
+  final-expression
+} while (exit-condition)
+ +

We would recommend for, at least to begin with, as it is probably the easiest for remembering everything — the initializer, exit-condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them.

+ +
+

Note: There are other loop types/features too, which are useful in advanced/specialized situations and beyond the scope of this article. If you want to go further with your loop learning, read our advanced Loops and iteration guide.

+
+ +

Conclusion

+ +

This article has revealed to you the basic concepts behind, and different options available when, looping code in JavaScript. You should now be clear on why loops are a good mechanism for dealing with repetitive code, and be raring to use them in your own examples!

+ +

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/conditionals","Learn/JavaScript/Building_blocks/Functions", "Learn/JavaScript/Building_blocks")}}

+ +

In this module

+ + +<gdiv></gdiv> diff --git a/files/es/learn/javascript/building_blocks/conditionals/index.html b/files/es/learn/javascript/building_blocks/conditionals/index.html new file mode 100644 index 0000000000..7a0fdcb91d --- /dev/null +++ b/files/es/learn/javascript/building_blocks/conditionals/index.html @@ -0,0 +1,778 @@ +--- +title: Tomando decisiones en tu código — condicionales +slug: Learn/JavaScript/Building_blocks/conditionals +tags: + - Aprendizaje + - Artículo + - Codificación + - Condicionales + - JavaScript + - Principiante +translation_of: Learn/JavaScript/Building_blocks/conditionals +--- +
+

{{LearnSidebar}}

+ +

{{NextMenu("Learn/JavaScript/Building_blocks/Looping_code", "Learn/JavaScript/Building_blocks")}}

+
+ +

En cualquier lenguaje de programación, el código necesita realizar decisiones y llevar a cabo diferentes acciones acordes dependiendo de distintas entradas. Por ejemplo, en un juego, si el el numero de vidas del jugador es 0, entonces se termina el juego. En una aplicación del clima, si se observa en la mañana, se despliega una gráfica del amanecer; muestra estrellas y una luna si es de noche. En este artículo, exploraremos cómo las llamadas declaraciones condicionales funcionan en JavaScript.

+ + + + + + + + + + + + +
Prerequisitos:Conocimientos básicos de informática, básico entendimiento de HTML y CSS, JavaScript primeros pasos.
Objetivo:Entender como se usan las extructuras condicionales en JavaScript. 
+ +

Puedes hacerlo en una condición..!

+ +

Los seres humanos (y otros animales) toman decisiones todo el tiempo que afectan sus vidas, desde la más insignificante ("¿Debería comer una galleta o dos?") hasta la más grande (¿Debería quedarme en mi país y trabajar en la granja de mi padre, o debería mudarme a Estados Unidos y estudiar astrofísica?). 

+ +

+ +

Declaraciones if ... else 

+ +

Echemos un vistazo a la declaración condicional más común que usarás en JavaScript.

+ +

 — El humilde if ... else statement.

+ +

Sintaxis if ... else básica. 

+ +

Una sintaxis básica if...else luce así. {{glossary("pseudocode")}}:

+ +
if (condición) {
+  código a ejecutar si la condición es verdadera
+} else {
+  ejecuta este otro código si la condición es falsa
+}
+ +

Aquí tenemos:

+ +
    +
  1. La palabra clave if seguida de unos paréntesis.
  2. +
  3. Una condición a probar, puesta dentro de los paréntesis (típicamente "¿es este valor mayor que este otro valor?", o "¿existe este valor?"). Esta condición usará los  operadores de comparación que hemos hablado en el módulo anterior y retorna un valor true o false (verdadero o falso).
  4. +
  5. Un conjunto de llaves, en las cuales tenemos algún código — puede ser cualquier código que deseemos, código que se ejecutará sólamente si la condición retorna true.
  6. +
  7. La palabra clave else.
  8. +
  9. Otro conjunto de llaves, dentro de las cuales tendremos otro código — puede ser cualquier código que deseemos, y sólo se ejecutará si la condición no es true.
  10. +
+ +

Este código es fácil de leer —  está diciendo "si (if)  la condición retorna verdadero (true),  entonces ejecute el código A, sino (else)  ejecute el código B"

+ +

Habrás notado que no tienes que incluir else y el segundo bloque de llaves — La siguiente declaración también es perfectmaente legal. 

+ +
if (condición) {
+  ejecuta el código de al ser verdadera la condición
+}
+
+ejecuta otro código
+ +

Sin embargo, hay que ser cuidadosos — en este caso, el segundo bloque no es controlado por una declaración condicional, así que siempre se ejecutará, sin importar si la condicional devuelve true o false. Esto no es necesariemente algo malo, pero puede ser algo que no quieras —  a menudo desearás ejecutar un bloque de código u otro, no ambos.

+ +

Como punto final, habrán ocaciones donde veas delcaraciones  if...else escritas sin un conjunto de llaves, de esta manera:

+ +
if (condición) ejecuta código de ser verdadero (true)
+else ejecuta este otro código 
+ +

Este código es perfectamente valido, pero no es recomendado usarlo — es mucho más fácil leer el código y determinar qué sucede haciendo uso de  las llaves para delimitar los bloques de código y usar varias líneas y sangrías.

+ +

Un ejemplo real

+ +

Para comprender mejor la sintaxis,  realicemos un ejemplo real. Imagínese a un niño a quien su madre o padre le pide ayuda con una tarea. El padre podría decir: "¡Hola, cariño! Si me ayudas yendo y haciendo las compras, te daré un subsidio adicional para que puedas pagar ese juguete que querías". En JavaScript, podríamos representar esto así:

+ +
let compraRealizada = false;
+
+if (compraRealizada === true) {
+  let subsidioAdicional = 10;
+} else {
+  let subsidioAdicional = 5;
+}
+ +

La variable compraRealizada escrita en este código dará siempre como resultado un retorno de valor  false,  lo cuál significa una desilusión para nuestro pobre hijo. Depende de nosotros proporcionar un mecanismo para que el padre cambie el valor de la variable compraRealizadatrue si el niño realizó la compra.

+ +
+

Nota: Podrás ver una versión más completa de este ejemplo en GitHub (también podrás verlo corriendo en vivo.)

+
+ +

else if

+ +

El último ejemplo nos proporcionó dos opciones o resultados, pero ¿qué ocurre si queremos más de dos?

+ +

Hay una forma de encadenar  opciones / resultados adicionales extras a if...else — usando else if. Cada opción extra requiere un bloque adicional para poner en medio de bloque if() { ... } y else { ... } — Vea el siguiente ejemplo un poco más complicado, que podría ser parte de una aplicación para un simple pronóstico del tiempo:

+ +
<label for="clima">Seleccione el tipo de clima de hoy: </label>
+<select id="clima">
+  <option value="">--Haga una elección--</option>
+  <option value="soleado">Soleado</option>
+  <option value="lluvioso">Lluvioso</option>
+  <option value="nevando">Nevando</option>
+  <option value="nublado">Nublado</option>
+</select>
+
+<p></p>
+ +
let seleccionar = document.querySelector('select');
+let parrafo = document.querySelector('p');
+
+seleccionar.addEventListener('change', establecerClima);
+
+function establecerClima() {
+  let eleccion = seleccionar.value;
+
+  if (eleccion === 'soleado') {
+    parrafo.textContent = 'El día esta agradable y soleado hoy. ¡Use pantalones cortos! Ve a la playa o al parque y come un helado.';
+  } else if (eleccion === 'lluvioso') {
+    parrafo.textContent = 'Está lloviendo, tome un abrigo para lluvia y un paraguas, y no se quede por fuera mucho tiempo.';
+  } else if (eleccion === 'nevando') {
+    parrafo.textContent = 'Está nevando ─ ¡está congelando! Lo mejor es quedarse en casa con una taza caliente de chocolate, o hacer un muñeco de nieve.';
+  } else if (eleccion === 'nublado') {
+    parrafo.textContent = 'No está lloviendo, pero el cielo está gris y nublado; podría llover en cualquier momento, así que lleve un saco solo por si acaso.';
+  } else {
+    parrafo.textContent = '';
+  }
+}
+
+
+ +

{{ EmbedLiveSample('else_if', '100%', 100, "", "", "hide-codepen-jsfiddle") }}

+ +
    +
  1. Aquí tenemos un elemento HTML {{htmlelement("select")}} que nos permite realizar varias elecciones sobre el clima, y un parrafo simple.
  2. +
  3. En el JavaScript, estamos almacenando una referencia para ambos elementos {{htmlelement("select")}} y {{htmlelement("p")}} , y añadiendo un Event Listener o en español un Detector de Eventos al elemento <select>  así cuando su valor cambie se ejecuta la función establecerClima().
  4. +
  5. Cuando la función es ejecutada, primero establecemos la variable eleccion con el valor obtenido del elemento <select>. Luego usamos una declaración condicinal  para mostrar distintos textos dentro del párrafo {{htmlelement("p")}} dependiendo del valor de la variable eleccion. Note  como todas las condicinales son probadas en los bloques else if() {...} , a excepción del primero, el cual es probado en el primer bloque if() {...}.
  6. +
  7. La ultima elección,  dentro del bloque else {...}, es básicamente  el "último recurso" como opción—  El código dentro de este bloque se ejecutará si nunguna de las condiciones es true. En este caso, sirve para vaciar el contenido del párrafo si nada ha sido seleccionado, por ejemplo, si el usuario decide elegir de nuevo  "--Haga una elección--" mostrado al inicio.
  8. +
+ +
+

Nota: Puedes encontrar  este ejemplo en GitHub (También podrás verlo correr en vivo.)

+
+ +

Una nota en los operadores de comparación 

+ +

Los operadores de comparación son usados para probar las condiciones dentro de nuestra declaración condicional. Vimos estos operadores en el artículo Matématica básica en JavaScript — Números y operadores. Nuestras opciones son:

+ + + +
+

Nota: Revisa el material en los enlaces previos para refrescar la memoria en estos temas. 

+
+ +

Queremos hacer una mención especial al probar los valores  (true/false) , y un patrón común que te encontrarás una y otra vez. Cualquier valor que no sea false, undefined, null, 0, NaN,  o una cadena vacía string ('') realmente retorna el valor true cuando es probada como una declaración condicional, por lo tanto puedes simplemente usar el nombre de una variable para probar si es  true, o si al menos existe  (i.e. no está definido.) Por ejemplo:

+ +
let queso = 'Cheddar';
+
+if (queso) {
+  console.log('¡Siii! Hay queso para hacer tostadas con queso.');
+} else {
+  console.log('No hay tostadas con queso para ti hoy :(.');
+}
+ +

En el ejemplo anterior la variable queso contiene el valor 'Cheddar', y como su valor está definido o no es false, undefined, null, 0, NaN y (' ') es considerado como true lo cual hará mostrar el mensaje dentro del primer bloque de llaves. 

+ +

Y, devolviéndonos al ejemplo previo del niño haciendo las compras para su padre, lo podrías haber escrito así:

+ +
let compraRealizada = false;
+
+if (compraRealizada) { //no necesitas especificar explícitamente '=== true'
+   let subsidioAdicional = 10;
+} else {
+   let subsidioAdicional = 5;
+}
+ +

Anidando if ... else

+ +

Está perfectamente permitido poner una declaración  if...else dentro de otra declaración if...else —  para anidarlas. Por ejemplo, podemos actualizar nuestra aplicación del clima para mostrar una serie de opciones dependiendo de cual sea la temperatura:

+ +
if (elección === 'soleado') {
+  if (temperatura < 86) {
+    parrafo.textContent = 'Está a ' + temperatura + ' grados afuera — agradable y soleado. Vamos a la playa, o al parque, y comer helado.';
+  } else if (temperatura >= 86) {
+    parrafo.textContent = 'Está a ' + temperatura + ' grados afuera — ¡QUÉ CALOR! Si deseas salir, asegúrate de aplicarte bloqueador solar.';
+  }
+}
+ +

Aunque el código funciona en conjunto, cada declaración  if...else funciona complentamente independiente del otro.

+ +

Operadores lógicos: AND, OR y NOT

+ +

Si quieres probar multiples condiciones sin escribir declaraciones  if...else anidados,  los operadores lógicos  pueden ayudarte. Cuando se usa en condiciones, los primeros dos hacen lo siguiente:

+ + + +

Para poner un ejemplo de  AND, el anterior código puede ser reescrito de esta manera:

+ +
if (eleccion === 'soleado' && temperatura < 86) {
+  parrafo.textContent = 'Está a ' + temperatura + ' grados afuera — agradable y soleado. Vamos a la playa, o al parque, y comer helado.';
+} else if (eleccion === 'soleado' && temperatura >= 86) {
+  parrafo.textContent = 'Está a ' + temperatura + ' grados afuera — ¡QUÉ CALOR! Si deseas salir, asegúrate de aplicarte bloqueador solar.';
+}
+ +

Así que por ejemplo, el primer bloque solo se ejecutará si la variable eleccion === 'soleado' temperatura < 86 devuelven un valor verdadero o true.

+ +

Observemos un ejemplo rápido del operador OR:

+ +
if (carritoDeHelados || estadoDeLaCasa === 'en llamas') {
+  console.log('Debes salir de la casa rápidamente.');
+} else {
+  console.log('Es mejor que te quedes dentro de casa');
+}
+ +

El último tipo de operador lógico, NOT, es expresado con el operador !, puede ser usado para negar una expresión. Vamos a combinarlo con el operador OR en el siguiente ejemplo:

+ +
if (!(carritoDeHelados || estadoDeLaCasa === 'en llamas')) {
+  console.log('Es mejor que te quedes dentro de casa');
+} else {
+  console.log('Debes salir de la casa rápidamente.');
+}
+ +

En el anterior ejemplo, si las declaraciones del operador OR retornan un valor true,  el operador NOT negará toda la expresión dentro de los paréntesis, por lo tanto retornará un valor false.

+ +

Puedes combinar los operadores que quieras dentro de las sentencias, en cualquier estructura. El siguiente ejemplo ejecuta el código dentro del condicional solo si ambas sentencias OR devuelven verdadero, lo que significa que la instrucción general AND devolverá verdadero:

+ +
if ((x === 5 || y > 3 || z <= 10) && (logueado || nombreUsuario === 'Steve')) {
+  // ejecuta el código
+}
+ +

Un error comun cuando se utiliza el operador OR en las declaraciones condicionales es intentar verificar el valor de la variable una sola vez, y luego darle una lista de valores que podrían retornar verdadero separados por  operadores ||. Por ejemplo:

+ +
if (x === 5 || 7 || 10 || 20) {
+  // ejecuta mi código
+}
+ +

En este caso la condición  if(...)  siempre evaluará a verdadero siendo que  7 (u otro valor que no sea 0) siempre será verdadero. Esta condición lo que realmente está diciendo es que "if x es igual a 5, o 7 es verdadero— lo cual siempre es". ¡Esto no es lógicamente lo que queremos!  Para hacer que esto funcione, tenemos que especificar una prueba completa para cada lado del operador OR:

+ +
if (x === 5 || x === 7 || x === 10 ||x === 20) {
+  // ejecuta mi código
+}
+ +

Declaraciones con switch

+ +

El condicional if...else hace un buen trabajo permitiéndonos realizar un buen código, pero esto viene con sus desventajas.  Hay variedad de casos donde necesitarás realizar varias elecciones, y cada una requiere una cantidad razonable de código para ser ejecutado y/o sus condicionales son complejas (i.e. operadores lógicos múltiples). Para los casos en los que solo se desea establecer una variable para una determinada opción de valores o imprimir una declaración particular dependiendo de una condición, la sintaxis puede ser un poco engorrosa, especialmente si se tiene una gran cantidad de opciones.

+ +

Para estos casos los switch statements son de gran ayuda — toman una sola expresión / valor como una entrada, y luego pasan a través de una serie de opciones hasta que encuentran una que coincida con ese valor, ejecutando el código correspondiente que va junto con ella. Aquí hay un pseudocódigo más para hacerte una idea:

+ +
switch (expresion) {
+  case choice1:
+    ejecuta este código
+    break;
+
+  case choice2:
+    ejecuta este código
+    break;
+
+  // Se pueden incluir todos los casos que quieras
+
+  default:
+    por si acaso, corre este código
+}
+ +

Aquí tenemos:

+ +
    +
  1. La palabra clave switch, seguida por un conjunto de paréntesis.
  2. +
  3. Una expresión o valor dentro de los paréntesis.
  4. +
  5. La palabra clave case, seguida de una elección con la expresión / valor que podría ser, seguido de dos puntos.
  6. +
  7. Algún código a correr si la elección coincide con la expresión.
  8. +
  9. Un declaración llamada break,  seguida de un punto y coma. Si la elección previa coincide con la expresión / valor, el explorador dejará de ejecutar el bloque de código aquí, y continuará a la siguiente línea de código. Si la opción anterior coincide con la expresión / valor, aquí el navegador deja de ejecutar el bloque de código  y pasa a cualquier código que aparezca debajo de la declaración de switch.
  10. +
  11. Como muchos otros casos, los que quieras.
  12. +
  13. La palabra clave default, seguido exactamente del mismo patrón de código que en los casos anteriores , excepto que el valor predeterminado no tiene opciónes después de él, y no es necesario que se use break porque no hay nada que ejecutar después de este bloque de todas formas. Esta es la opción predeterminada o por defecto que se ejecuta si ninguna de las opciones coincide.
  14. +
+ +
+

Nota: No tiene que incluir la sección default; se puede omitir con seguridad si no hay posibilidades de que la expresión  termine igualando un valor desconocido. Sin embargo, si existe la posibilidad de que esto ocurra, debe incluirlo para evitar casos desconocidos o comportamientos extraños en tu código.

+
+ +

Un ejemplo con switch

+ +

Let's have a look at a real example — we'll rewrite our weather forecast application to use a switch statement instead:

+ +
<label for="weather">Select the weather type today: </label>
+<select id="weather">
+  <option value="">--Make a choice--</option>
+  <option value="sunny">Sunny</option>
+  <option value="rainy">Rainy</option>
+  <option value="snowing">Snowing</option>
+  <option value="overcast">Overcast</option>
+</select>
+
+<p></p>
+ +
let select = document.querySelector('select');
+let para = document.querySelector('p');
+
+select.addEventListener('change', setWeather);
+
+
+function setWeather() {
+  let choice = select.value;
+
+  switch (choice) {
+    case 'sunny':
+      para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
+      break;
+    case 'rainy':
+      para.textContent = 'Rain is falling outside; take a rain coat and a brolly, and don\'t stay out for too long.';
+      break;
+    case 'snowing':
+      para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
+      break;
+    case 'overcast':
+      para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
+      break;
+    default:
+      para.textContent = '';
+  }
+}
+ +

{{ EmbedLiveSample('A_switch_example', '100%', 100, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Nota: Tambien puedes encontrar este ejemplo en GitHub (tambien puedes verlo en ejecución aquí.)

+
+ +

Operador Ternario

+ +

Hay una última sintaxis que queremos presentarte antes de que juegues con algunos ejemplos. El operador ternario o condicional es una pequeña sintaxis que prueba una condición y devuelve un valor/expresión, si es true, y otro si es false — Esto puede ser útil en algunas situaciones, y puede ocupar mucho menos código que un bloque if...else si simplemente tienes dos opciones que se eligen a través de una condición true/false. El pseudocódigo se ve así:

+ +
( condición ) ? ejecuta este código : ejecuta este código en su lugar
+ +

Veamos un ejemplo simple:

+ +
let greeting = ( isBirthday ) ? 'Happy birthday Mrs. Smith — we hope you have a great day!' : 'Good morning Mrs. Smith.';
+ +

Aquí tenemos una variable llamada isBirthday — si esta es true, le damos a nuestro invitado un mensaje de feliz cumpleaños; si no, le damos el saludo diario estándar.

+ +

Ejemplo con operador ternario

+ +

No solo puedes establecer valores variables con el operador ternario; También puedes ejecutar funciones o líneas de código — lo que quieras. El siguiente ejemplo muestra un selector de tema simple donde el estilo del sitio se aplica utilizando un operador ternario.

+ +
<label for="theme">Select theme: </label>
+<select id="theme">
+  <option value="white">White</option>
+  <option value="black">Black</option>
+</select>
+
+<h1>This is my website</h1>
+ +
let select = document.querySelector('select');
+let html = document.querySelector('html');
+document.body.style.padding = '10px';
+
+function update(bgColor, textColor) {
+  html.style.backgroundColor = bgColor;
+  html.style.color = textColor;
+}
+
+select.onchange = function() {
+  ( select.value === 'black' ) ? update('black','white') : update('white','black');
+}
+
+ +

{{ EmbedLiveSample('Ternary_operator_example', '100%', 300, "", "", "hide-codepen-jsfiddle") }}

+ +

Aquí tenemos un elemento {{htmlelement('select')}} para elegir un tema (blanco o negro), más un simple (black or white), plus a simple {{htmlelement('h1')}} para mostrar el título de un sitio web. También tenemos una función llamada update(), que toma dos colores como parámetros (entradas). El color de fondo del sitio web se establece en el primer color proporcionado y el color del texto se establece en el segundo color proporcionado.

+ +

Finalmente, también tenemos un detector de eventos onchange que sirve para ejecutar una función que contiene un operador ternario. Comienza con una condición de prueba — select.value === 'black'. Si esto devuelve true, ejecutamos la función update() con parámetros de blanco y negro, lo que significa que terminamos con un color de fondo negro y un color de texto blanco. Si devuelve false, ejecutamos las función update() con parámetros de blanco y negro, lo que significa que el color del sitio está invertido.

+ +
+

Nota: También puedes encontrar este ejemplo en GitHub (y verlo en ejecución aquí.)

+
+ +

Aprendizaje activo: Un calendario simple

+ +

En este ejemplo, nos ayudará a terminar una aplicación de calendario simple. En el código tienes:

+ + + +

Necesitamos que escriba una declaración condicional dentro de la función del controlador onchange justo debajo del comentario // ADD CONDITIONAL HERE. Debería:

+ +
    +
  1. Mire el mes seleccionado (almacenado en la variable choice. Este será el valor del elemento <select> después de que cambie el valor, por ejemplo "January")
  2. +
  3. Establezca una variable llamada days para que sea igual al número de días del mes seleccionado. Para hacer esto, tendrá que buscar el número de días en cada mes del año. Puede ignorar los años bisiestos a los efectos de este ejemplo.
  4. +
+ +

Sugerencias:

+ + + +

Si comete un error, siempre puede restablecer el ejemplo con el botón "Reset". Si se queda realmente atascado, presione "Show solution" para ver una solución.

+ + + +

{{ EmbedLiveSample('Playable_code', '100%', 1110, "", "", "hide-codepen-jsfiddle") }}

+ +

Aprendizaje activo: Más opciones de colores!

+ +

In this example, you are going to take the ternary operator example we saw earlier and convert the ternary operator into a switch statement that will allow us to apply more choices to the simple website. Look at the {{htmlelement("select")}} — this time you'll see that it has not two theme options, but five. You need to add a switch statement just underneath the // ADD SWITCH STATEMENT comment:

+ + + +

If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.

+ + + +

{{ EmbedLiveSample('Playable_code_2', '100%', 950, "", "", "hide-codepen-jsfiddle") }}

+ +

Conclusión

+ +

And that's all you really need to know about conditional structures in JavaScript right now! I'm sure you'll have understood these concepts and worked through the examples with ease; if there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

+ +

Revisa también

+ + + +

{{NextMenu("Learn/JavaScript/Building_blocks/Looping_code", "Learn/JavaScript/Building_blocks")}}

+ +

En este módulo

+ + diff --git a/files/es/learn/javascript/building_blocks/construyendo_tu_propia_funcion/index.html b/files/es/learn/javascript/building_blocks/construyendo_tu_propia_funcion/index.html new file mode 100644 index 0000000000..5f9bcc7c8b --- /dev/null +++ b/files/es/learn/javascript/building_blocks/construyendo_tu_propia_funcion/index.html @@ -0,0 +1,252 @@ +--- +title: Construye tu propia función +slug: Learn/JavaScript/Building_blocks/Construyendo_tu_propia_funcion +tags: + - Aprender + - Artículo + - Construir + - Funciones + - Guía + - JavaScript + - Principiante + - Tutorial +translation_of: Learn/JavaScript/Building_blocks/Build_your_own_function +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Functions","Learn/JavaScript/Building_blocks/Return_values", "Learn/JavaScript/Building_blocks")}}
+ +

Con la mayor parte de la teoría esencial tratada en el artículo anterior, este artículo proporciona experiencia práctica. Aquí obtendrás práctica construyendo tu propia función personalizada. En el camino, también explicaremos algunos detalles útiles sobre cómo tratar las funciones.

+ + + + + + + + + + + + +
Prerequisites:Conocimientos básicos de computación, una comprensión básica de HTML y CSS, JavaScript first steps, Functions — reusable blocks of code.
Objective:Para proporcionar algo de práctica en la construcción de una función personalizada, y explicar algunos detalles asociados más útiles.
+ +

Aprendizaje activo: construyamos una función.

+ +

La función personalizada que vamos a construir se llamará displayMessage(). Mostrará un cuadro de mensaje personalizado en una página web y actuará como un reemplazo personalizado para la función de alert() incorporada de un navegador. Hemos visto esto antes, pero solo refresquemos nuestros recuerdos. Escriba lo siguiente en la consola de JavaScript de su navegador, en la página que desee:

+ +
alert('This is a message');
+ +

La función alert tiene un argumento — el string que se muestra en la alerta. Prueba a variar el string para cambiar el mensaje.

+ +

La función alert es limitada: pueder cambiar el mensaje, pero no puedes cambiar de manera sencilla nada más, como el color, icono o cualquier otra cosa. Construiremos uno que resultará ser más divertido.

+ +
+

Nota: Este ejemplo debería funcionar bien en todos los navegadores modernos, pero el estilo puede parecer un poco divertido en los navegadores un poco más antiguos. Te recomendamos que hagas este ejercicio en un navegador moderno como Firefox, Opera o Chrome.

+
+ +

La función básica

+ +

Para empezar, vamos a poner juntos una función básica.

+ +
+

Nota: Para las convenciones de nombres de las funciones, debes seguir las mismas reglas que convecion de nombres de variables. Esto está bien, ya que puede distinguirlos: los nombres de las funciones aparecen entre paréntesis después de ellos y las variables no.

+
+ +
    +
  1. Comience accediendo al archivo function-start.html y haciendo una copia local. Verás que el HTML es simple  — el body unicamente tiene un botón. También hemos propocionado algunos estilos básicos de CSS para customizar el mensaje y un elemento  {{htmlelement("script")}} vacío para poner nuestro JavaScript dentro.
  2. +
  3. Luego añade lo siguiente dentro del elemento <script>: +
    function displayMessage() {
    +
    +}
    + Comenzamos con la palabra clave función, lo que significa que estamos definiendo una función. A esto le sigue el nombre que queremos darle a nuestra función, un conjunto de paréntesis y un conjunto de llaves. Todos los parámetros que queremos darle a nuestra función van dentro de los paréntesis, y el código que se ejecuta cuando llamamos a la función va dentro de las llaves.
  4. +
  5. Finalmente, agregue el siguiente código dentro de las llaves: +
    let html = document.querySelector('html');
    +
    +let panel = document.createElement('div');
    +panel.setAttribute('class', 'msgBox');
    +html.appendChild(panel);
    +
    +let msg = document.createElement('p');
    +msg.textContent = 'This is a message box';
    +panel.appendChild(msg);
    +
    +let closeBtn = document.createElement('button');
    +closeBtn.textContent = 'x';
    +panel.appendChild(closeBtn);
    +
    +closeBtn.onclick = function() {
    +  panel.parentNode.removeChild(panel);
    +}
    +
  6. +
+ +

Esto es un montón de código por el que pasar, así que lo guiaremos paso a paso.

+ +

La primera línea usa un función DOM API llamada {{domxref("document.querySelector()")}} para seleccionar el elemento {{htmlelement("html")}} y guardar una referencia a él en una variable llamada html, por lo que podemos hacer cosas para más adelante:

+ +
let html = document.querySelector('html');
+ +

La siguiente sección usa otra función del DOM API llamada {{domxref("Document.createElement()")}} para crear un elemento {{htmlelement("div")}} y guardar una referencia a él en una variable llamada panel. Este elemento será el contenedor exterior de nuestro cuadro de mensaje.

+ +

Entonces usamos otra función del API DOM llamada {{domxref("Element.setAttribute()")}} para configurar un atributo a class en nuestro panel con un valor de msgBox. Esto es para facilitar el estilo del elemento. — Si echas un vistazo al CSS en la página, verás que estamos utilizando un selector de clases.msgBox para dar estilo al al contenedor del mensaje.

+ +

Finalmente, llamamos a una función del DOM llamada {{domxref("Node.appendChild()")}} en la variable html que hemos guardado anteriormente, que anida un elemento dentro del otro como hijo de él. Hemos especificado el panel <div> como el hijo que queremos añadir dentro del elemento <html>. Debemos hacer esto ya que el elemento que creamos no aparecerá en la página por sí solo — tenemos que especificar donde ponerlo.

+ +
let panel = document.createElement('div');
+panel.setAttribute('class', 'msgBox');
+html.appendChild(panel);
+ +

Las siguientes dos secciones hacen uso de las mismas funciones createElement()appendChild() que ya vimos para crear dos nuevos elementos — un {{htmlelement("p")}} y un {{htmlelement("button")}} — e insertarlo en la página como un hijo del panel <div>. Usamos su propiedad  {{domxref("Node.textContent")}} — que representa el contenido de texto de un elemento: para insertar un mensaje dentro del párrafo y una 'x' dentro del botón. Este botón será lo que necesita hacer clic / activar cuando el usuario quiera cerrar el cuadro de mensaje.

+ +
let msg = document.createElement('p');
+msg.textContent = 'This is a message box';
+panel.appendChild(msg);
+
+let closeBtn = document.createElement('button');
+closeBtn.textContent = 'x';
+panel.appendChild(closeBtn);
+ +

Finalmente, usamos el manejador de evento {{domxref("GlobalEventHandlers.onclick")}} para hacerlo de modo que cuando se haga clic en el botón, se ejecute algún código para eliminar todo el panel de la página, para cerrar el cuadro de mensaje.

+ +

Brevemente, el handler onclick es una propiedad disponible en el botón (o, de hecho, en cualquier elemento de la página) que se puede configurar en una función para especificar qué código ejecutar cuando se hace clic en el botón. Aprenderás mucho más sobre esto en nuestro artículo de eventos posteriores. Estamos haciendo el handler onclick igual que una función anónima, que contiene el código para ejecutar cuando se ha hecho click en el botón. La línea dentro de la función usa la función del DOM API {{domxref("Node.removeChild()")}}  para especificar que queremos eliminar un elemento secundario específico del elemento HTML— en este caso el panel <div>.

+ +
closeBtn.onclick = function() {
+  panel.parentNode.removeChild(panel);
+}
+ +

Básicamente, todo este bloque de código está generando un bloque de HTML que se ve así, y lo está insertando en la página:

+ +
<div class="msgBox">
+  <p>This is a message box</p>
+  <button>x</button>
+</div>
+ +

Fue un montón de código con el que trabajar: ¡no te preocupes demasiado si no recuerdas exactamente cómo funciona todo ahora! La parte principal en la que queremos centrarnos aquí es la estructura y el uso de la función, pero queríamos mostrar algo interesante para este ejemplo.

+ +

Llamando a la función

+ +

Ahora tienes la definición de tu función escrita en tu elemento <script> bien, pero no hará nada tal como está.

+ +
    +
  1. Intente incluir la siguiente línea debajo de su función para llamarla: +
    displayMessage();
    + Esta línea invoca la función, haciéndola correr inmediatamente. Cuando guarde el código y lo vuelva a cargar en el navegador, verá que el pequeño cuadro de mensaje aparece inmediatamente, solo una vez. Después de todo, solo lo llamamos una vez.
  2. +
  3. +

    Ahora abra las herramientas de desarrollo de su navegador en la página de ejemplo, vaya a la consola de JavaScript y escriba la línea nuevamente allí, ¡verá que aparece nuevamente! Así que esto es divertido: ahora tenemos una función reutilizable que podemos llamar en cualquier momento que queramos.

    + +

    Pero probablemente queremos que aparezca en respuesta a las acciones del usuario y del sistema. En una aplicación real, tal cuadro de mensaje probablemente se llamará en respuesta a la disponibilidad de nuevos datos, a un error, al usuario que intenta eliminar su perfil ("¿está seguro de esto?"), O al usuario que agrega un nuevo contacto y la operación completando con éxito ... etc.

    + +

    En esta demostración, obtendremos el cuadro de mensaje que aparecerá cuando el usuario haga clic en el botón.

    +
  4. +
  5. Elimina la línea anterior que agregaste.
  6. +
  7. A continuación, seleccionaremos el botón y guardaremos una referencia a él en una variable. Agregue la siguiente línea a su código, encima de la definición de la función: +
    let btn = document.querySelector('button');
    +
  8. +
  9. Finalmente, agregue la siguiente línea debajo de la anterior: +
    btn.onclick = displayMessage;
    + De una forma similar que nuestra línea dentro de la función closeBtn.onclick..., aquí estamos llamando a algún código en respuesta a un botón al hacer clic. Pero en este caso, en lugar de llamar a una función anónima que contiene algún código, estamos llamando directamente a nuestro nombre de función.
  10. +
  11. Intente guardar y actualizar la página: ahora debería ver aparecer el cuadro de mensaje cuando hace clic en el botón.
  12. +
+ +

Quizás te estés preguntando por qué no hemos incluido los paréntesis después del nombre de la función. Esto se debe a que no queremos llamar a la función inmediatamente, solo después de hacer clic en el botón. Si intentas cambiar la línea a

+ +
btn.onclick = displayMessage();
+ +

y al guardar y volver a cargar, verás que aparece el cuadro de mensaje sin hacer clic en el botón. Los paréntesis en este contexto a veces se denominan "operador de invocación de función". Solo los utiliza cuando desea ejecutar la función inmediatamente en el ámbito actual. Del mismo modo, el código dentro de la función anónima no se ejecuta inmediatamente, ya que está dentro del alcance de la función.

+ +

Si has intentado el último experimento, asegúrate de deshacer el último cambio antes de continuar.

+ +

Mejora de la función con parámetros.

+ +

Tal como está, la función aún no es muy útil, no queremos mostrar el mismo mensaje predeterminado cada vez. Mejoremos nuestra función agregando algunos parámetros, permitiéndonos llamarla con algunas opciones diferentes.

+ +
    +
  1. En primer lugar, actualice la primera línea de la función: +
    function displayMessage() {
    + to this: + +
    function displayMessage(msgText, msgType) {
    + Ahora, cuando llamamos a la función, podemos proporcionar dos valores variables dentro de los paréntesis para especificar el mensaje que se mostrará en el cuadro de mensaje y el tipo de mensaje que es.
  2. +
  3. Para utilizar el primer parámetro, actualiza la siguiente línea dentro de su función: +
    msg.textContent = 'This is a message box';
    + to + +
    msg.textContent = msgText;
    +
  4. +
  5. Por último, pero no menos importante, ahora necesita actualizar su llamada de función para incluir un texto de mensaje actualizado. Cambia la siguiente línea: +
    btn.onclick = displayMessage;
    + to this block: + +
    btn.onclick = function() {
    +  displayMessage('Woo, this is a different message!');
    +};
    + Si queremos especificar parámetros dentro de paréntesis para la función a la que estamos llamando, no podemos llamarla directamente, necesitamos colocarla dentro de una función anónima para que no esté en el ámbito inmediato y, por lo tanto, no se llame de inmediato. Ahora no se llamará hasta que se haga clic en el botón.
  6. +
  7. Vuelva a cargar e intenta el código nuevamente y verás que aún funciona bien, ¡excepto que ahora también puede variar el mensaje dentro del parámetro para obtener diferentes mensajes mostrados en el cuadro!
  8. +
+ +

Un parámetro más complejo.

+ +

En el siguiente parámetro. Este va a implicar un poco más de trabajo: lo configuraremos de modo que, dependiendo de la configuración del parámetro msgType, la función mostrará un icono diferente y un color de fondo diferente.

+ +
    +
  1. En primer lugar, descargue los iconos necesarios para este ejercicio (warningchat) de GitHub. Guárdalos en una nueva carpeta llamada icons en la misma localización que tu HTML. + +
    Nota: los iconos warningchat que se encuentran en iconfinder.com, han sido diseñados por Nazarrudin Ansyari. Gracias!
    +
  2. +
  3. A continuación, encuentra el CSS dentro de tu archivo HTML. Haremos algunos cambios para dar paso a los iconos. Primero, actualiza el ancho de .msgBox desde: +
    width: 200px;
    + to + +
    width: 242px;
    +
  4. +
  5. Luego, añade las siguientes líneas dentro de la regla.msgBox p { ... }: +
    padding-left: 82px;
    +background-position: 25px center;
    +background-repeat: no-repeat;
    +
  6. +
  7. Ahora necesitamos añadir código a la función displayMessage() para manejar la visualización de los iconos. Agrega el siguiente bloque justo encima de la llave de cierre (}) de tu función : +
    if (msgType === 'warning') {
    +  msg.style.backgroundImage = 'url(icons/warning.png)';
    +  panel.style.backgroundColor = 'red';
    +} else if (msgType === 'chat') {
    +  msg.style.backgroundImage = 'url(icons/chat.png)';
    +  panel.style.backgroundColor = 'aqua';
    +} else {
    +  msg.style.paddingLeft = '20px';
    +}
    +
  8. +
  9. Aquí, si el parámetro msgType se establece como 'warning', se muestra el icono de advertencia y el color de fondo del panel se establece en rojo. Si se establece en 'chat', se muestra el icono de chat y el color de fondo del panel se establece en azul aguamarina. Si el parámetro msgType no está configurado en absoluto (o en algo diferente), entonces la parte else { ... } del código entra en juego, y al párrafo simplemente se le da un relleno predeterminado y ningún icono, sin el conjunto de colores del panel de fondo ya sea. Esto proporciona un estado predeterminado si no se proporciona ningún parámetro msgType , lo que significa que es un parámetro opcional.
  10. +
  11. Vamos a probar nuestra función actualizada , prueba a actualizar la llamada a displayMessage() con esto: +
    displayMessage('Woo, this is a different message!');
    + to one of these: + +
    displayMessage('Your inbox is almost full — delete some mails', 'warning');
    +displayMessage('Brian: Hi there, how are you today?','chat');
    + Puedes ver cuán útil se está volviendo nuestra (ahora no tan) poca función.
  12. +
+ +
+

Nota: Si estas teniendo problemas con el ejemplo, sientente libre para coger el ejemplo para trabajar con él, finished version on GitHub (see it running live también), o pídenos ayuda.

+
+ +

Conclusión

+ +

¡Felicidades por llegar al final! Este artículo lo llevó a través de todo el proceso de creación de una función personalizada y práctica, que con un poco más de trabajo podría trasplantarse en un proyecto real. En el siguiente artículo resumiremos las funciones explicando otro concepto esencial relacionado: valores de retorno.

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Functions","Learn/JavaScript/Building_blocks/Return_values", "Learn/JavaScript/Building_blocks")}}

+ +

En este módulo

+ + diff --git a/files/es/learn/javascript/building_blocks/eventos/index.html b/files/es/learn/javascript/building_blocks/eventos/index.html new file mode 100644 index 0000000000..7bdb81768a --- /dev/null +++ b/files/es/learn/javascript/building_blocks/eventos/index.html @@ -0,0 +1,578 @@ +--- +title: Introducción a eventos +slug: Learn/JavaScript/Building_blocks/Eventos +translation_of: Learn/JavaScript/Building_blocks/Events +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
+ +

Los eventos son acciones u ocurrencias que suceden en el sistema que está programando y que el sistema le informa para que pueda responder de alguna manera si lo desea. Por ejemplo, si el usuario hace clic en un botón en una página web, es posible que desee responder a esa acción mostrando un cuadro de información. En este artículo, discutiremos algunos conceptos importantes que rodean los eventos y veremos cómo funcionan en los navegadores. Este no será un estudio exhaustivo; solo lo que necesitas saber en esta etapa.

+ + + + + + + + + + + + +
Prerrequisitos:Conocimientos básicos de informática, entendimiento básico de HTML y CSS, Primeros pasos con JavaScript.
Objetivo:Comprender la teoría fundamental de los eventos, cómo funcionan en los navegadores y cómo los eventos pueden diferir en distintos entornos de programación.
+ +

Una serie de eventos afortunados

+ +

Como se mencionó anteriormente, los eventos son acciones u ocurrencias que suceden en el sistema que está programando — el sistema disparará una señal de algún tipo cuando un evento ocurra y también proporcionará un mecanismo por el cual se puede tomar algún tipo de acción automáticamente (p.e., ejecutando algún código) cuando se produce el evento. Por ejemplo, en un aeropuerto cuando la pista está despejada para que despegue un avión, se comunica una señal al piloto y, como resultado, comienzan a pilotar el avión.

+ +

+ +

En el caso de la Web, los eventos se desencadenan dentro de la ventana del navegador y tienden a estar unidos a un elemento específico que reside en ella — podría ser un solo elemento, un conjunto de elementos, el documento HTML cargado en la pestaña actual o toda la ventana del navegador. Hay muchos tipos diferentes de eventos que pueden ocurrir, por ejemplo:

+ + + +

Se deducirá de esto (y echar un vistazo a MDN Referencia de eventos) que hay muchos eventos a los que se puede responder.

+ +

Cada evento disponible tiene un controlador de eventos, que es un bloque de código (generalmente una función JavaScript definida por el usuario) que se ejecutará cuando se active el evento. Cuando dicho bloque de código se define para ejecutarse en respuesta a un disparo de evento, decimos que estamos registrando un controlador de eventos. Tenga en cuenta que los controladores de eventos a veces se llaman oyentes de eventos — son bastante intercambiables para nuestros propósitos, aunque estrictamente hablando, trabajan juntos. El oyente escucha si ocurre el evento y el controlador es el código que se ejecuta en respuesta a que ocurra.

+ +
+

Nota: Es útil tener en cuenta que los eventos web no son parte del lenguaje central de JavaScript: se definen como parte de las API integradas en el navegador.

+
+ +

Un ejemplo simple

+ +

Veamos un ejemplo simple para explicar lo que queremos decir aquí. Ya has visto eventos y controladores de eventos en muchos de los ejemplos de este curso, pero vamos a recapitular solo para consolidar nuestro conocimiento. En el siguiente ejemplo, tenemos un solo {{htmlelement ("button")}}, que cuando se presiona, hará que el fondo cambie a un color aleatorio:

+ +
<button>Cambiar color</button>
+ + + +

El JavaScript se ve así:

+ +
const btn = document.querySelector('button');
+
+function random(number) {
+  return Math.floor(Math.random() * (number+1));
+}
+
+btn.onclick = function() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

En este código, almacenamos una referencia al botón dentro de una variable llamada btn, usando la función {{domxref ("Document.querySelector ()")}}. También definimos una función que devuelve un número aleatorio. La tercera parte del código es el controlador de eventos. La variable btn apunta a un elemento <button>, y este tipo de objeto tiene una serie de eventos que pueden activarse y, por lo tanto, los controladores de eventos están disponibles. Estamos escuchando el disparo del evento "click", estableciendo la propiedad del controlador de eventos onclick para que sea igual a una función anónima que contiene código que generó un color RGB aleatorio y establece el <body> color de fondo igual a este.

+ +

Este código ahora se ejecutará cada vez que se active el evento "click" en el elemento <button>, es decir, cada vez que un usuario haga clic en él.

+ +

El resultado de ejemplo es el siguiente:

+ +

{{ EmbedLiveSample('A_simple_example', '100%', 200, "", "", "hide-codepen-jsfiddle") }}

+ +

No son solo páginas web

+ +

Otra cosa que vale la pena mencionar en este punto es que los eventos no son particulares de JavaScript — la mayoría de los lenguajes de programación tienen algún tipo de modelo de eventos, y la forma en que funciona a menudo diferirá de la forma en que funciona en JavaScript. De hecho, el modelo de eventos en JavaScript para páginas web difiere del modelo de eventos para JavaScript, ya que se utiliza en otros entornos.

+ +

Por ejemplo, Node.js es un entorno en tiempo de ejecución de JavaScript muy popular que permite a los desarrolladores usar JavaScript para crear aplicaciones de red y del lado del servidor. El modelo de eventos de Node.js se basa en que los oyentes (listeners) escuchen eventos y los emisores (emitters) emitan eventos periódicamente — no suena tan diferentes, pero el código es bastante diferente, haciendo uso de funciones como on() para registrar un oyente de eventos, y once() para registrar un oyente de eventos que anula el registro después de que se haya ejecutado una vez. The documentos de eventos de conexión HTTP proporcionan un buen ejemplo de uso.

+ +

Como otro ejemplo, ahora también puede usar JavaScript para crear complementos de navegadores — mejoras de funcionalidad del navegador — utilizando una tecnología llamada WebExtensions. El modelo de eventos es similar al modelo de eventos web, pero un poco diferente — las propiedades de los oyentes de eventos se escriben en camel-case (ej. onMessage en lugar de onmessage), y deben combinarse con la función addListener. Consulte la página runtime.onMessage para ver un ejemplo.

+ +

No necesita comprender nada sobre otros entornos en esta etapa de su aprendizaje; solo queríamos dejar en claro que los eventos pueden diferir en diferentes entornos de programación.

+ +

Diferentes formas de uso de eventos

+ +

Hay muchas maneras distintas en las que puedes agregar event listeners a los sitios web, que se ejecutara cuando el evento asociado se dispare. En esta sección, revisaremos los diferentes mecanismos y discutiremos cuales deberias usar..

+ +

Propiedades de manejadores de eventos

+ +

Estas son las propiedades que existen, que contienen codigo de manejadores de eventos(Event Handler)  que vemos frecuentemente durante el curso.. Volviendo al ejemplo de arriba:

+ +
var btn = document.querySelector('button');
+
+btn.onclick = function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

La propiedad onclick es la propiedad del manejador de eventos que está siendo usada en esta situación. Es escencialmente una propiedad como cualquier otra disponible en el botón (por ejemplo: btn.textContent, or btn.style), pero es de un tipo especial — cuando lo configura para ser igual a algún código, ese código se ejecutará cuando el evento se dispare en el botón.

+ +

You could also set the handler property to be equal to a named function name (like we saw in Build your own function). The following would work just the same:

+ +
var btn = document.querySelector('button');
+
+function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.onclick = bgChange;
+ +

There are many different event handler properties available. Let's do an experiment.

+ +

First of all, make a local copy of random-color-eventhandlerproperty.html, and open it in your browser. It's just a copy of the simple random color example we've been playing with already in this article. Now try changing btn.onclick to the following different values in turn, and observing the results in the example:

+ + + +

Some events are very general and available nearly anywhere (for example an onclick handler can be registered on nearly any element), whereas some are more specific and only useful in certain situations (for example it makes sense to use onplay only on specific elements, such as {{htmlelement("video")}}).

+ +

Inline event handlers — don't use these

+ +

You might also see a pattern like this in your code:

+ +
<button onclick="bgChange()">Press me</button>
+
+ +
function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

The earliest method of registering event handlers found on the Web involved event handler HTML attributes (aka inline event handlers) like the one shown above — the attribute value is literally the JavaScript code you want to run when the event occurs. The above example invokes a function defined inside a {{htmlelement("script")}} element on the same page, but you could also insert JavaScript directly inside the attribute, for example:

+ +
<button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button>
+ +

You'll find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.

+ +

For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.

+ +

Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would very quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:

+ +
var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length; i++) {
+  buttons[i].onclick = bgChange;
+}
+ +

Note that another option here would be to use the forEach() built-in method available on all Array objects:

+ +
buttons.forEach(function(button) {
+  button.onclick = bgChange;
+});
+ +
+

Note: Separating your programming logic from your content also makes your site more friendly to search engines.

+
+ +

addEventListener() and removeEventListener()

+ +

The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 Events Specification, which provides browsers with a new function — addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this:

+ +
var btn = document.querySelector('button');
+
+function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

Inside the addEventListener() function, we specify two parameters — the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectly appropriate to put all the code inside the addEventListener() function, in an anonymous function, like this:

+ +
btn.addEventListener('click', function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+});
+ +

This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, removeEventListener(), which removes a previously added listener. For example, this would remove the listener set in the first code block in this section:

+ +
btn.removeEventListener('click', bgChange);
+ +

This isn't significant for simple, small programs, but for larger, more complex programs it can improve efficiency to clean up old unused event handlers. Plus, for example, this allows you to have the same button performing different actions in different circumstances — all you've got to do is add/remove event handlers as appropriate.

+ +

Second, you can also register multiple handlers for the same listener. The following two handlers would not be applied:

+ +
myElement.onclick = functionA;
+myElement.onclick = functionB;
+ +

As the second line would overwrite the value of onclick set by the first. This would work, however:

+ +
myElement.addEventListener('click', functionA);
+myElement.addEventListener('click', functionB);
+ +

Both functions would now run when the element is clicked.

+ +

In addition, there are a number of other powerful features and options available with this event mechanism. These are a little out of scope for this article, but if you want to read up on them, have a look at the addEventListener() and removeEventListener() reference pages.

+ +

What mechanism should I use?

+ +

Of the three mechanisms, you definitely shouldn't use the HTML event handler attributes — these are outdated, and bad practice, as mentioned above.

+ +

The other two are relatively interchangeable, at least for simple uses:

+ + + +

The main advantages of the third mechanism are that you can remove event handler code if needed, using removeEventListener(), and you can add multiple listeners of the same type to elements if required. For example, you can call addEventListener('click', function() { ... }) on an element multiple times, with different functions specified in the second argument. This is impossible with event handler properties because any subsequent attempts to set a property will overwrite earlier ones, e.g.:

+ +
element.onclick = function1;
+element.onclick = function2;
+etc.
+ +
+

Note: If you are called upon to support browsers older than Internet Explorer 8 in your work, you may run into difficulties, as such ancient browsers use different event models from newer browsers. But never fear, most JavaScript libraries (for example jQuery) have built-in functions that abstract away cross-browser differences. Don't worry about this too much at this stage in your learning journey.

+
+ +

Other event concepts

+ +

In this section, we will briefly cover some advanced concepts that are relevant to events. It is not important to understand these fully at this point, but it might serve to explain some code patterns you'll likely come across from time to time.

+ +

Event objects

+ +

Sometimes inside an event handler function, you might see a parameter specified with a name such as event, evt, or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:

+ +
function bgChange(e) {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  e.target.style.backgroundColor = rndCol;
+  console.log(e);
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

Here you can see that we are including an event object, e, in the function, and in the function setting a background color style on e.target — which is the button itself. The target property of the event object is always a reference to the element that the event has just occurred upon. So in this example, we are setting a random background color on the button, not the page.

+ +
+

Note: You can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function. e/evt/event are most commonly used by developers because they are short and easy to remember. It's always good to stick to a standard.

+
+ +

e.target is incredibly useful when you want to set the same event handler on multiple elements and do something to all of them when an event occurs on them. You might, for example, have a set of 16 tiles that disappear when they are clicked on. It is useful to always be able to just set the thing to disappear as e.target, rather than having to select it in some more difficult way. In the following example (see useful-eventtarget.html for the full source code; also see it running live here), we create 16 {{htmlelement("div")}} elements using JavaScript. We then select all of them using {{domxref("document.querySelectorAll()")}}, then loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when clicked:

+ +
var divs = document.querySelectorAll('div');
+
+for (var i = 0; i < divs.length; i++) {
+  divs[i].onclick = function(e) {
+    e.target.style.backgroundColor = bgChange();
+  }
+}
+ +

The output is as follows (try clicking around on it — have fun):

+ + + +

{{ EmbedLiveSample('Hidden_example', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

+ +

Most event handlers you'll encounter just have a standard set of properties and functions (methods) available on the event object (see the {{domxref("Event")}} object reference for a full list). Some more advanced handlers, however, add specialist properties containing extra data that they need to function. The Media Recorder API, for example, has a dataavailable event, which fires when some audio or video has been recorded and is available for doing something with (for example saving it, or playing it back). The corresponding ondataavailable handler's event object has a data property available containing the recorded audio or video data to allow you to access it and do something with it.

+ +

Preventing default behavior

+ +

Sometimes, you'll come across a situation where you want to stop an event doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and press the submit button, the natural behaviour is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified.)

+ +

The trouble comes when the user has not submitted the data correctly — as a developer, you'll want to stop the submission to the server and give them an error message telling them what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example.

+ +

First, a simple HTML form that requires you to enter your first and last name:

+ +
<form>
+  <div>
+    <label for="fname">First name: </label>
+    <input id="fname" type="text">
+  </div>
+  <div>
+    <label for="lname">Last name: </label>
+    <input id="lname" type="text">
+  </div>
+  <div>
+     <input id="submit" type="submit">
+  </div>
+</form>
+<p></p>
+ + + +

Now some JavaScript — here we implement a very simple check inside an onsubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. If they are, we call the preventDefault() function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong:

+ +
var form = document.querySelector('form');
+var fname = document.getElementById('fname');
+var lname = document.getElementById('lname');
+var submit = document.getElementById('submit');
+var para = document.querySelector('p');
+
+form.onsubmit = function(e) {
+  if (fname.value === '' || lname.value === '') {
+    e.preventDefault();
+    para.textContent = 'You need to fill in both names!';
+  }
+}
+ +

Obviously, this is pretty weak form validation — it wouldn't stop the user validating the form with spaces or numbers entered into the fields, for example — but it is ok for example purposes. The output is as follows:

+ +

{{ EmbedLiveSample('Preventing_default_behavior', '100%', 140, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Note: for the full source code, see preventdefault-validation.html (also see it running live here.)

+
+ +

Event bubbling and capture

+ +

The final subject to cover here is something that you'll not come across often, but it can be a real pain if you don't understand it. Event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. Let's look at an example to make this easier — open up the show-video-box.html example in a new tab (and the source code in another tab.) It is also available live below:

+ + + +

{{ EmbedLiveSample('Hidden_video_example', '100%', 500, "", "", "hide-codepen-jsfiddle") }}

+ +

This is a pretty simple example that shows and hides a {{htmlelement("div")}} with a {{htmlelement("video")}} element inside it:

+ +
<button>Display video</button>
+
+<div class="hidden">
+  <video>
+    <source src="rabbit320.mp4" type="video/mp4">
+    <source src="rabbit320.webm" type="video/webm">
+    <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+  </video>
+</div>
+ +

When the {{htmlelement("button")}} is clicked, the video is displayed, by changing the class attribute on the <div> from hidden to showing (the example's CSS contains these two classes, which position the box off the screen and on the screen, respectively):

+ +
btn.onclick = function() {
+  videoBox.setAttribute('class', 'showing');
+}
+ +

We then add a couple more onclick event handlers — the first one to the <div> and the second one to the <video>. The idea is that when the area of the <div> outside the video is clicked, the box should be hidden again; when the video itself is clicked, the video should start to play.

+ +
videoBox.onclick = function() {
+  videoBox.setAttribute('class', 'hidden');
+};
+
+video.onclick = function() {
+  video.play();
+};
+ +

But there's a problem — currently, when you click the video it starts to play, but it causes the <div> to also be hidden at the same time. This is because the video is inside the <div> — it is part of it — so clicking on the video actually runs both the above event handlers.

+ +

Bubbling and capturing explained

+ +

When an event is fired on an element that has parent elements (e.g. the {{htmlelement("video")}} in our case), modern browsers run two different phases — the capturing phase and the bubbling phase.

+ +

In the capturing phase:

+ + + +

In the bubbling phase, the exact opposite occurs:

+ + + +

+ +

(Click on image for bigger diagram)

+ +

In modern browsers, by default, all event handlers are registered in the bubbling phase. So in our current example, when you click the video, the click event bubbles from the <video> element outwards to the <html> element. Along the way:

+ + + +

Fixing the problem with stopPropagation()

+ +

This is annoying behavior, but there is a way to fix it! The standard event object has a function available on it called stopPropagation(), which when invoked on a handler's event object makes it so that handler is run, but the event doesn't bubble any further up the chain, so no more handlers will be run.

+ +

We can, therefore, fix our current problem by changing the second handler function in the previous code block to this:

+ +
video.onclick = function(e) {
+  e.stopPropagation();
+  video.play();
+};
+ +

You can try making a local copy of the show-video-box.html source code and having a go at fixing it yourself, or looking at the fixed result in show-video-box-fixed.html (also see the source code here).

+ +
+

Note: Why bother with both capturing and bubbling? Well, in the bad old days when browsers were much less cross-compatible than they are now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is the one modern browsers implemented.

+
+ +
+

Note: As mentioned above, by default all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the capturing phase instead, you can do so by registering your handler using addEventListener(), and setting the optional third property to true.

+
+ +

Event delegation

+ +

Bubbling also allows us to take advantage of event delegation — this concept relies on the fact that if you want some code to run when you click on any one of a large number of child elements, you can set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Remember earlier that we said bubbling involves checking the element the event is fired on for an event handler first, then moving up to the element's parent, etc.?

+ +

A good example is a series of list items — if you want each one of them to pop up a message when clicked, you can set the click event listener on the parent <ul>, and events will bubble from the list items to the <ul>.

+ +

This concept is explained further on David Walsh's blog, with multiple examples — see How JavaScript Event Delegation Works.

+ +

Conclusion

+ +

You should now know all you need to know about web events at this early stage. As mentioned above, events are not really part of the core JavaScript — they are defined in browser Web APIs.

+ +

Also, it is important to understand that the different contexts in which JavaScript is used tend to have different event models — from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.

+ +

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}

+ +

In this module

+ + diff --git a/files/es/learn/javascript/building_blocks/functions/index.html b/files/es/learn/javascript/building_blocks/functions/index.html new file mode 100644 index 0000000000..d05ae34969 --- /dev/null +++ b/files/es/learn/javascript/building_blocks/functions/index.html @@ -0,0 +1,400 @@ +--- +title: Funciones — bloques de código reutilizables +slug: Learn/JavaScript/Building_blocks/Functions +tags: + - API + - Funciones + - JavaScript + - Métodos + - Navegador +translation_of: Learn/JavaScript/Building_blocks/Functions +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}
+ +

Otro concepto esencial en la codificación son las funciones, que te permiten almacenar un fragmento de código que realiza una única tarea dentro de un bloque definido, y luego llamar a ese código siempre que lo necesites utilizando un único comando breve -- en lugar de tener que escribir el mismo codigo varias veces. En este artículo exploraremos conceptos fundamentales detrás de funciones tales como sintaxis básica, cómo invocarlas y definirlas, alcance(scope) y parámetros.

+ + + + + + + + + + + + +
Prerequisites:Conocimientos basicos de informatica, conocimiento basico de   HTML y CSS, JavaScript first steps.
Objective:Entender los conceptos fundamentales detras de las funciones JavaScript.
+ +

¿Dónde encuentro las funciones? 

+ +

En JavaScript vas a encontrar funciones por todos lados. De hecho, nosotros hemos usados funciones todo el tiempo a lo largo del curso; solo que no hemos hablado mucho sobre ellas. Ahora es el momento, igual, para comenzar a hablar explicitamente sobre las funciones y explorar su sintaxis.

+ +

Básicamente cada vez que haces uso de código JavaScript que contiene parentesis como () y no estás usando estructuras de lenguaje como for loop, while, do, do while, estás usando una función! 

+ +

Funciones incluídas en los navegadores

+ +

A lo largo de este curso hemos usado muchas funciones incluídas del navegador. Por ejemplo, cuando manipulamos una cadena de texto o string:

+ +
let miTexto = 'Soy una cadena de texto!';
+let nuevaCadena = miTexto.replace('cadena', 'ensalada');
+console.log(nuevaCadena);
+// la función de cadena de texto replace() toma una cadena,
+// reemplaza una palabra por otra, y devuelve
+// una nueva cadena con el reemplazo hecho.
+ +

O cada vez que manipulamos un array:

+ +
let miArray = ['Yo', 'amo', 'el', 'chocolate', 'y', 'las', 'ranas'];
+let armarCadena = miArray.join(' ');
+console.log(armarCadena);
+// La función join() toma un array,
+// une todos sus elementos en una cadena o string
+// y devuelve esta nueva cadena.
+ +

O cada vez que generamos un número al azar:

+ +
var miNumero = Math.random();
+console.log(miNumero);
+// La función Math.random() genera un número aleatorio
+// entre 0 and 1 y devuelve ese número.
+
+ +

...estamos usando una función!

+ +
+

Nota: Sientase libre de ingresar esas líneas de código en la consola JavaScript de su navegador, para familiarizarse con sus funcionalidades. 

+
+ +

El lenguaje JavaScript contiene muchas funciones integradas que te permiten realizar cosas muy utilies sin escribir el código tu mismo. De hecho, parte del código que llamas (una palabra elegante para decir correr o ejecutar) cuando invocas una función integrada puede no estar escrita en JavaScript —muchas de estas funciones están llamando partes del código del navegador de fondo, que está escrito principalmente en lenguajes de sistema de bajo nivel como C ++, no en lenguajes web como JavaScript.

+ +

Bear in mind that some built-in browser functions are not part of the core JavaScript language — some are defined as part of browser APIs, which build on top of the default language to provide even more functionality (refer to this early section of our course for more descriptions). We'll look at using browser APIs in more detail in a later module.

+ +

Functions versus methods

+ +

One thing we need to clear up before we move on — technically speaking, built in browser functions are not functions — they are methods. This sounds a bit scary and confusing, but don't worry — the words function and method are largely interchangeable, at least for our purposes, at this stage in your learning.

+ +

The distinction is that methods are functions defined inside objects. Built-in browser functions (methods) and variables (which are called properties) are stored inside structured objects, to make the code more efficient and easier to handle.

+ +

You don't need to learn about the inner workings of structured JavaScript objects yet — you can wait until our later module that will teach you all about the inner workings of objects, and how to create your own. For now, we just wanted to clear up any possible confusion of method versus function — you are likely to meet both terms as you look at the available related resources across the Web.

+ +

Custom functions

+ +

You've also seen a lot of custom functions in the course so far — functions defined in your code, not inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom function. In our random-canvas-circles.html example (see also the full source code) from our loops article, we included a custom draw() function that looked like this:

+ +
function draw() {
+  ctx.clearRect(0,0,WIDTH,HEIGHT);
+  for (var i = 0; i < 100; i++) {
+    ctx.beginPath();
+    ctx.fillStyle = 'rgba(255,0,0,0.5)';
+    ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+    ctx.fill();
+  }
+}
+ +

This function draws 100 random circles inside an {{htmlelement("canvas")}} element. Every time we want to do that, we can just invoke the function with this

+ +
draw();
+ +

rather than having to write all that code out again every time we want to repeat it. And functions can contain whatever code you like — you can even call other functions from inside functions. The above function for example calls the random() function three times, which is defined by the following code:

+ +
function random(number) {
+  return Math.floor(Math.random()*number);
+}
+ +

We needed this function because the browser's built-in Math.random() function only generates a random decimal number between 0 and 1. We wanted a random whole number between 0 and a specified number.

+ +

Invoking functions

+ +

You are probably clear on this by now, but just in case ... to actually use a function after it has been defined, you've got to run — or invoke — it. This is done by including the name of the function in the code somewhere, followed by parentheses.

+ +
function myFunction() {
+  alert('hello');
+}
+
+myFunction()
+// calls the function once
+ +

Anonymous functions

+ +

You may see functions defined and invoked in slightly different ways. So far we have just created a function like so:

+ +
function myFunction() {
+  alert('hello');
+}
+ +

But you can also create a function that doesn't have a name:

+ +
function() {
+  alert('hello');
+}
+ +

This is called an anonymous function — it has no name! It also won't do anything on its own. You generally use an anonymous function along with an event handler, for example the following would run the code inside the function whenever the associated button is clicked:

+ +
var myButton = document.querySelector('button');
+
+myButton.onclick = function() {
+  alert('hello');
+}
+ +

The above example would require there to be a {{htmlelement("button")}} element available on the page to select and click. You've already seen this structure a few times throughout the course, and you'll learn more about and see it in use in the next article.

+ +

You can also assign an anonymous function to be the value of a variable, for example:

+ +
var myGreeting = function() {
+  alert('hello');
+}
+ +

This function could now be invoked using:

+ +
myGreeting();
+ +

This effectively gives the function a name; you can also assign the function to be the value of multiple variables, for example:

+ +
var anotherGreeting = function() {
+  alert('hello');
+}
+ +

This function could now be invoked using either of

+ +
myGreeting();
+anotherGreeting();
+ +

But this would just be confusing, so don't do it! When creating functions, it is better to just stick to this form:

+ +
function myGreeting() {
+  alert('hello');
+}
+ +

You will mainly use anonymous functions to just run a load of code in response to an event firing — like a button being clicked — using an event handler. Again, this looks something like this:

+ +
myButton.onclick = function() {
+  alert('hello');
+  // I can put as much code
+  // inside here as I want
+}
+ +

Function parameters

+ +

Some functions require parameters to be specified when you are invoking them — these are values that need to be included inside the function parentheses, which it needs to do its job properly.

+ +
+

Note: Parameters are sometimes called arguments, properties, or even attributes.

+
+ +

As an example, the browser's built-in Math.random() function doesn't require any parameters. When called, it always returns a random number between 0 and 1:

+ +
var myNumber = Math.random();
+ +

The browser's built-in string replace() function however needs two parameters — the substring to find in the main string, and the substring to replace that string with:

+ +
var myText = 'I am a string';
+var newString = myText.replace('string', 'sausage');
+ +
+

Note: When you need to specify multiple parameters, they are separated by commas.

+
+ +

It should also be noted that sometimes parameters are optional — you don't have to specify them. If you don't, the function will generally adopt some kind of default behavior. As an example, the array join() function's parameter is optional:

+ +
var myArray = ['I', 'love', 'chocolate', 'frogs'];
+var madeAString = myArray.join(' ');
+// returns 'I love chocolate frogs'
+var madeAString = myArray.join();
+// returns 'I,love,chocolate,frogs'
+ +

If no parameter is included to specify a joining/delimiting character, a comma is used by default.

+ +

Function scope and conflicts

+ +

Let's talk a bit about {{glossary("scope")}} — a very important concept when dealing with functions. When you create a function, the variables and other things defined inside the function are inside their own separate scope, meaning that they are locked away in their own separate compartments, unreachable from inside other functions or from code outside the functions.

+ +

The top level outside all your functions is called the global scope. Values defined in the global scope are accessible from everywhere in the code.

+ +

JavaScript is set up like this for various reasons — but mainly because of security and organization. Sometimes you don't want variables to be accessible from everywhere in the code — external scripts that you call in from elsewhere could start to mess with your code and cause problems because they happen to be using the same variable names as other parts of the code, causing conflicts. This might be done maliciously, or just by accident.

+ +

For example, say you have an HTML file that is calling in two external JavaScript files, and both of them have a variable and a function defined that use the same name:

+ +
<!-- Excerpt from my HTML -->
+<script src="first.js"></script>
+<script src="second.js"></script>
+<script>
+  greeting();
+</script>
+ +
// first.js
+var name = 'Chris';
+function greeting() {
+  alert('Hello ' + name + ': welcome to our company.');
+}
+ +
// second.js
+var name = 'Zaptec';
+function greeting() {
+  alert('Our company is called ' + name + '.');
+}
+ +

Both functions you want to call are called greeting(), but you can only ever access the second.js file's greeting() function — it is applied to the HTML later on in the source code, so its variable and function overwrite the ones in first.js.

+ +
+

Note: You can see this example running live on GitHub (see also the source code).

+
+ +

Keeping parts of your code locked away in functions avoids such problems, and is considered best practice.

+ +

It is a bit like a zoo. The lions, zebras, tigers, and penguins are kept in their own enclosures, and only have access to the things inside their enclosures — in the same manner as the function scopes. If they were able to get into other enclosures, problems would occur. At best, different animals would feel really uncomfortable inside unfamiliar habitats — a lion or tiger would feel terrible inside the penguins' watery, icy domain. At worst, the lions and tigers might try to eat the penguins!

+ +

+ +

The zoo keeper is like the global scope — he or she has the keys to access every enclosure, to restock food, tend to sick animals, etc.

+ +

Active learning: Playing with scope

+ +

Let's look at a real example to demonstrate scoping.

+ +
    +
  1. First, make a local copy of our function-scope.html example. This contains two functions called a() and b(), and three variables — x, y, and z — two of which are defined inside the functions, and one in the global scope. It also contains a third function called output(), which takes a single parameter and outputs it in a paragraph on the page.
  2. +
  3. Open the example up in a browser and in your text editor.
  4. +
  5. Open the JavaScript console in your browser developer tools. In the JavaScript console, enter the following command: +
    output(x);
    + You should see the value of variable x output to the screen.
  6. +
  7. Now try entering the following in your console +
    output(y);
    +output(z);
    + Both of these should return an error along the lines of "ReferenceError: y is not defined". Why is that? Because of function scope — y and z are locked inside the a() and b() functions, so output() can't access them when called from the global scope.
  8. +
  9. However, what about when it's called from inside another function? Try editing a() and b() so they look like this: +
    function a() {
    +  var y = 2;
    +  output(y);
    +}
    +
    +function b() {
    +  var z = 3;
    +  output(z);
    +}
    + Save the code and reload it in your browser, then try calling the a() and b() functions from the JavaScript console: + +
    a();
    +b();
    + You should see the y and z values output in the page. This works fine, as the output() function is being called inside the other functions — in the same scope as the variables it is printing are defined in, in each case. output() itself is available from anywhere, as it is defined in the global scope.
  10. +
  11. Now try updating your code like this: +
    function a() {
    +  var y = 2;
    +  output(x);
    +}
    +
    +function b() {
    +  var z = 3;
    +  output(x);
    +}
    + Save and reload again, and try this again in your JavaScript console: + +
    a();
    +b();
    + Both the a() and b() call should output the value of x — 1. These work fine because even though the output() calls are not in the same scope as x is defined in, x is a global variable so is available inside all code, everywhere.
  12. +
  13. Finally, try updating your code like this: +
    function a() {
    +  var y = 2;
    +  output(z);
    +}
    +
    +function b() {
    +  var z = 3;
    +  output(y);
    +}
    + Save and reload again, and try this again in your JavaScript console: + +
    a();
    +b();
    + This time the a() and b() calls will both return that annoying "ReferenceError: z is not defined" error — this is because the output() calls and the variables they are trying to print are not defined inside the same function scopes — the variables are effectively invisible to those function calls.
  14. +
+ +
+

Note: The same scoping rules do not apply to loop (e.g. for() { ... }) and conditional blocks (e.g. if() { ... }) — they look very similar, but they are not the same thing! Take care not to get these confused.

+
+ +
+

Note: The ReferenceError: "x" is not defined error is one of the most common you'll encounter. If you get this error and you are sure that you have defined the variable in question, check what scope it is in.

+
+ + + +

Functions inside functions

+ +

Keep in mind that you can call a function from anywhere, even inside another function.  This is often used as a way to keep code tidy — if you have a big complex function, it is easier to understand if you break it down into several sub-functions:

+ +
function myBigFunction() {
+  var myValue;
+
+  subFunction1();
+  subFunction2();
+  subFunction3();
+}
+
+function subFunction1() {
+  console.log(myValue);
+}
+
+function subFunction2() {
+  console.log(myValue);
+}
+
+function subFunction3() {
+  console.log(myValue);
+}
+
+ +

Just make sure that the values being used inside the function are properly in scope. The example above would throw an error ReferenceError: myValue is not defined, because although the myValue variable is defined in the same scope as the function calls, it is not defined inside the function definitions — the actual code that is run when the functions are called. To make this work, you'd have to pass the value into the function as a parameter, like this:

+ +
function myBigFunction() {
+  var myValue = 1;
+
+  subFunction1(myValue);
+  subFunction2(myValue);
+  subFunction3(myValue);
+}
+
+function subFunction1(value) {
+  console.log(value);
+}
+
+function subFunction2(value) {
+  console.log(value);
+}
+
+function subFunction3(value) {
+  console.log(value);
+}
+ +

Conclusion

+ +

This article has explored the fundamental concepts behind functions, paving the way for the next one in which we get practical and take you through the steps to building up your own custom function.

+ +

See also

+ + + + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Looping_code","Learn/JavaScript/Building_blocks/Build_your_own_function", "Learn/JavaScript/Building_blocks")}}

+ +

In this module

+ + +<gdiv></gdiv> diff --git a/files/es/learn/javascript/building_blocks/galeria_de_imagenes/index.html b/files/es/learn/javascript/building_blocks/galeria_de_imagenes/index.html new file mode 100644 index 0000000000..205f1a11aa --- /dev/null +++ b/files/es/learn/javascript/building_blocks/galeria_de_imagenes/index.html @@ -0,0 +1,144 @@ +--- +title: Galería de imágenes +slug: Learn/JavaScript/Building_blocks/Galeria_de_imagenes +translation_of: Learn/JavaScript/Building_blocks/Image_gallery +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}
+ +

Ahora que hemos analizado los bloques de construcción fundamentales de JavaScript, pongamos a prueba tu conocimiento de bucles, funciones, condicionales y eventos, creando un elemento que comumente vemos en muchos sitios web, una Galería de imágenes "motorizada" por JavaScript .

+ + + + + + + + + + + + +
Prerequisitos:Antes de intentar esta evaluación deberías de haber trabajado con todos los artículos en éste módulo.
Objetivo:Evaluar la comprensión de los bucles, funciones, condicionales y eventos de JavaScript..
+ +

Punto de partida

+ +

Para realizar esta evaluación, debería descárgarse archivoZip para el ejemplo, descomprímalo en algún lugar de su computadora y haga el ejercicio localmente para empezar.

+ +

Opcionalmente, puedes usar un sitio como JSBin o Glitch para realizar tu evaluación. Puede pegar el HTML, CSS y JavaScript dentro de uno de estos editores online. Si el editor en línea que está utilizando no tiene paneles JavaScript / CSS separados, siéntase libre de ponerlos en línea <script> / <style> elementos dentro de la página HTML.

+ +
+

Nota: Si se atascascas con algo, entonces pregúntenos para ayudarlo — vea la sección de {{anch("evaluación o ayuda adicional")}} al final de esta página.

+
+ +

Resumen del proyecto

+ +

Ha sido provisto con algún contenido de HTML, CSS e imágenes, también algunas líneas de código en JavaScript; necesitas escribir las líneas de código en JavaScript necesatio para transformarse en un programa funcional. El  HTML body luce así:

+ +
<h1>Image gallery example</h1>
+
+<div class="full-img">
+  <img class="displayed-img" src="images/pic1.jpg">
+  <div class="overlay"></div>
+  <button class="dark">Darken</button>
+</div>
+
+<div class="thumb-bar">
+
+</div>
+ +

El ejemplo se ve así:

+ +

+ + + +

Las partes más interesantes del archivo example's CSS :

+ + + +

Your JavaScript needs to:

+ + + +

To give you more of an idea, have a look at the finished example (no peeking at the source code!)

+ +

Steps to complete

+ +

The following sections describe what you need to do.

+ +

Looping through the images

+ +

We've already provided you with lines that store a reference to the thumb-bar <div> inside a constant called thumbBar, create a new <img> element, set its src attribute to a placeholder value xxx, and append this new <img> element inside thumbBar.

+ +

You need to:

+ +
    +
  1. Put the section of code below the "Looping through images" comment inside a loop that loops through all 5 images — you just need to loop through five numbers, one representing each image.
  2. +
  3. In each loop iteration, replace the xxx placeholder value with a string that will equal the path to the image in each case. We are setting the value of the src attribute to this value in each case. Bear in mind that in each case, the image is inside the images directory and its name is pic1.jpg, pic2.jpg, etc.
  4. +
+ +

Adding an onclick handler to each thumbnail image

+ +

In each loop iteration, you need to add an onclick handler to the current newImage — this handler should find the value of the src attribute of the current image. Set the src attribute value of the displayed-img <img> to the src value passed in as a parameter.

+ +

Writing a handler that runs the darken/lighten button

+ +

That just leaves our darken/lighten <button> — we've already provided a line that stores a reference to the <button> in a constant called btn. You need to add an onclick handler that:

+ +
    +
  1. Checks the current class name set on the <button> — you can again achieve this by using getAttribute().
  2. +
  3. If the class name is "dark", changes the <button> class to "light" (using setAttribute()), its text content to "Lighten", and the {{cssxref("background-color")}} of the overlay <div> to "rgba(0,0,0,0.5)".
  4. +
  5. If the class name not "dark", changes the <button> class to "dark", its text content back to "Darken", and the {{cssxref("background-color")}} of the overlay <div> to "rgba(0,0,0,0)".
  6. +
+ +

The following lines provide a basis for achieving the changes stipulated in points 2 and 3 above.

+ +
btn.setAttribute('class', xxx);
+btn.textContent = xxx;
+overlay.style.backgroundColor = xxx;
+ +

Hints and tips

+ + + +

Assessment or further help

+ +

If you would like your work assessed, or are stuck and want to ask for help:

+ +
    +
  1. Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch.
  2. +
  3. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: +
      +
    • A descriptive title such as "Assessment wanted for Image gallery".
    • +
    • Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment.
    • +
    • A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into — it's very hard to help someone with a coding problem if you can't see their code.
    • +
    • A link to the actual task or assessment page, so we can find the question you want help with.
    • +
    +
  4. +
+ +

{{PreviousMenu("Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}

+ +

In this module

+ + diff --git a/files/es/learn/javascript/building_blocks/index.html b/files/es/learn/javascript/building_blocks/index.html new file mode 100644 index 0000000000..de9e7c7c4a --- /dev/null +++ b/files/es/learn/javascript/building_blocks/index.html @@ -0,0 +1,71 @@ +--- +title: Elementos básicos de JavaScript +slug: Learn/JavaScript/Building_blocks +tags: + - CodingScripting + - Condicionales + - Evaluación + - Funciones + - Guía + - JavaScript + - Landing + - NeedsTranslation + - Principiante + - TopicStub + - bucles + - eventos + - introducción + - 'l10n:priority' + - modulo +translation_of: Learn/JavaScript/Building_blocks +--- +
{{LearnSidebar}}
+ +

En este módulo, continuamos nuestra cobertura de todas las características clave de JavaScript, tornando nuestra atención a tipos de código comúnmente encontrados tales como enunciados condicionales, bucles (loops), funciones, y eventos. Ya has visto estas cosas en este curso, pero solo de pasada aquí lo hablaremos mas explícitamente.

+ +

Quieres transformarte en un desarrollador web front-end?

+ +

Hemos reunido un curso que incluye toda la información esencial que necesitas para trabajar hacia tu objetivo.

+ +

Empieza aquí

+ +

Pre-requisitos

+ +

Antes de empezar este módulo, deberías ya tener alguna familiaridad con lo básico de HTML y CSS,  y también deberías haber trabajado todos lo módulos previos, JavaScript primeros pasos.

+ +
+

Nota: Si estas trabajando en una computadora/tablet/otro dispositivo donde no tienes la capacidad de crear tus propios archivos, podrías practicar (la mayoría de) los ejemplos de código en un programa en linea tales como JSBin o Thimble.

+
+ +

Guías

+ +
+
 Tomando decisiones en tu código — condicionales
+
En cualquier lenguaje de programación, el código necesita tomar decisiones y efectuar acciones consiguientemente dependiendo de las diferentes ordenes ingresadas. Por ejemplo, en un juego, si el numero de vidas del jugador es 0, entonces se termina el juego. En una aplicación del clima, si esta siendo vista por la mañana, muestra un gráfico del amanecer; muestra estrellas y una luna si es de noche. En este artículo exploraremos como los condicionales estructuran el trabajo en Javascript.
+
Bucles de código
+
A veces necesitas que una tarea se haga más de una vez. Por ejemplo, revisar toda una lista de nombres. En programación, los bucles ('loops' en inglés) hacen este trabajo muy bien. Aca veremos la estructura de loops en Javascript.
+
Funciones — bloques de código reusables
+
Otro concepto fundamental en código es funciones. Funciones te permite almacenar una pieza de código que ejecuta una sola tarea dentro de un bloque definido, y después llamar ese código cuando lo necesitas usando un comando corto  en lugar de tener que escribir el mismo código varias veces. En este articulo exploraremos conceptos fundamentales detrás de las funciones tales como sintaxis básica, cómo invocar y definir funciones, ámbito o alcance (scope), y parámetros.
+
Crea tu propia función
+
Con la información presentada en el artículo anterior, este artículo, pretende demostrar una parte práctica. Se podrá desarrollar una función propia, y durante el desarrollo se presentarán algunos consejos prácticos y útiles para trabajar con funciones.
+
 Una función devuelve valores
+
Un concepto fundamental que ha de tenerse en cuenta, es que las funciones pueden devolver valores al finalizar su ejecución, aunque algunas funciones también pueden no devolver ningún valor. Es importante entender como son esos valores, qué tipos pueden tener y cómo aprovechar el valor devuelto por la función en el programa.
+
Introducción a eventos
+
Los eventos son acciones u ocurrencias que aparecen durante la ejecución del programa, y que son reportadas por el sistema, de forma que se pueda responder a los eventos de la forma deseada. Por ejemplo, si un usuario hace un click en un botón de una página web, puede que se quiera que ese evento inicie una acción en el que se muestre cierta información en un cuadro de información.  En este último artículo se presentarán y describirán los conceptos necesarios con respecto a los eventos, y como funcionan en un navegador.
+
+ +

Evaluaciones

+ +

La siguiente evaluación probara tu entendimiento de lo básico de Javascript cubierto en las guias anteriores.

+ +
+
Galeria de imagen
+
Ahora que hemos visto los bloques constructores fundamentales de JavaScript, probaremos tus conocimientos en bucles, funciones, condicionales y eventos construyendo un item bastante común en muchos sitios web — una galería de imágenes creada con JavaScript. 
+
+ +

Ver también

+ +
+
Aprender JavaScript
+
Un excelente recurso para aspirantes a desarrolladores web — Aprenda JavaScript en un entorno interactivo, con lecciones cortas y pruebas interactivas, guiadas por una evaluación automatizada. Las primeras 40 lecciones son gratuitas, y el curso completo está disponible por un pequeño pago único.
+
diff --git a/files/es/learn/javascript/building_blocks/return_values/index.html b/files/es/learn/javascript/building_blocks/return_values/index.html new file mode 100644 index 0000000000..2602a7217f --- /dev/null +++ b/files/es/learn/javascript/building_blocks/return_values/index.html @@ -0,0 +1,168 @@ +--- +title: Una función retorna valores +slug: Learn/JavaScript/Building_blocks/Return_values +translation_of: Learn/JavaScript/Building_blocks/Return_values +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Build_your_own_function","Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}
+ +

Hay un último concepto esencial para que discutamos en este curso, para cerrar nuestra visión de las funciones: — lo valores que se devuelven. Algunas funciones no devuelven un valor significativo después de su finalización, pero otras sí, y es importante comprender cuáles son sus valores, cómo utilizarlos en su código y cómo hacer que sus propias funciones personalizadas devuelvan valores útiles. Cubriremos todos estos a continuación.

+ + + + + + + + + + + + +
Prerequisites: +

Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps, Functions — reusable blocks of code.

+
Objective:To understand function return values, and how to make use of them.
+ +

¿Qué son los valores de retorno?

+ +

Los valores de retorno son exactamente como suenan: los valores devueltos por la función cuando se completa. Ya has alcanzado los valores de retorno varias veces, aunque es posible que no hayas pensado en ellos explícitamente. Volvamos a un código familiar:

+ +
var myText = 'I am a string';
+var newString = myText.replace('string', 'sausage');
+console.log(newString);
+// la función de cadena replace () toma una cadena,
+// sustituyendo una subcadena con otra y devoviendo
+// ​​una cadena nueva con la sustitución realizada
+ +

Vimos exactamente este bloque de código en nuestro primer artículo de función. Estamos invocando la función replace () en la cadena myText, y le pasamos dos parámetros: la subcadena a encontrar y la subcadena con la que reemplazarla. Cuando esta función se completa (termina de ejecutarse), devuelve un valor, que es una nueva cadena con el reemplazo realizado. En el código anterior, estamos guardando este valor de retorno como el valor de la variable newString.

+ +

Si observa la página de referencia MDN de la función de reemplazo, verá una sección llamada Valor de retorno. Es muy útil conocer y comprender qué valores devuelven las funciones, por lo que tratamos de incluir esta información siempre que sea posible.

+ +

Algunas funciones no devuelven un valor de retorno como tal (en nuestras páginas de referencia, el valor de retorno aparece como void o undefined en tales casos). Por ejemplo, en la función displayMessage () que creamos en el artículo anterior, no se devuelve ningún valor específico como resultado de la función que se invoca. Simplemente hace que aparezca un cuadro en algún lugar de la pantalla, ¡eso es todo!

+ +

Generalmente, se usa un valor de retorno donde la función es un paso intermedio en un cálculo de algún tipo. Quieres llegar a un resultado final, que involucra algunos valores. Esos valores deben ser calculados por una función, que luego devuelve los resultados para que puedan usarse en la siguiente etapa del cálculo.

+ +

Using return values in your own functions

+ +

To return a value from a custom function, you need to use ... wait for it ... the return keyword. We saw this in action recently in our random-canvas-circles.html example. Our draw() function draws 100 random circles somewhere on an HTML {{htmlelement("canvas")}}:

+ +
function draw() {
+  ctx.clearRect(0,0,WIDTH,HEIGHT);
+  for (var i = 0; i < 100; i++) {
+    ctx.beginPath();
+    ctx.fillStyle = 'rgba(255,0,0,0.5)';
+    ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+    ctx.fill();
+  }
+}
+ +

Inside each loop iteration, three calls are made to the random() function, to generate a random value for the current circle's x coordinate, y coordinate, and radius, respectively. The random() function takes one parameter — a whole number — and it returns a whole random number between 0 and that number. It looks like this:

+ +
function randomNumber(number) {
+  return Math.floor(Math.random()*number);
+}
+ +

This could be written as follows:

+ +
function randomNumber(number) {
+  var result = Math.floor(Math.random()*number);
+  return result;
+}
+ +

But the first version is quicker to write, and more compact.

+ +

We are returning the result of the calculation Math.floor(Math.random()*number) each time the function is called. This return value appears at the point the function was called, and the code continues. So for example, if we ran the following line:

+ +
ctx.arc(random(WIDTH), random(HEIGHT), random(50), 0, 2 * Math.PI);
+ +

and the three random() calls returned the values 500, 200, and 35, respectively, the line would actually be run as if it were this:

+ +
ctx.arc(500, 200, 35, 0, 2 * Math.PI);
+ +

The function calls on the line are run first and their return values substituted for the function calls, before the line itself is then executed.

+ +

Active learning: our own return value function

+ +

Let's have a go at writing our own functions featuring return values.

+ +
    +
  1. First of all, make a local copy of the function-library.html file from GitHub. This is a simple HTML page containing a text {{htmlelement("input")}} field and a paragraph. There's also a {{htmlelement("script")}} element in which we have stored a reference to both HTML elements in two variables. This little page will allow you to enter a number into the text box, and display different numbers related to it in the paragraph below.
  2. +
  3. Let's add some useful functions to this <script> element. Below the existing two lines of JavaScript, add the following function definitions: +
    function squared(num) {
    +  return num * num;
    +}
    +
    +function cubed(num) {
    +  return num * num * num;
    +}
    +
    +function factorial(num) {
    +  var x = num;
    +  while (x > 1) {
    +    num *= x-1;
    +    x--;
    +  }
    +  return num;
    +}
    + The squared() and cubed() functions are fairly obvious — they return the square or cube of the number given as a parameter. The factorial() function returns the factorial of the given number.
  4. +
  5. Next, we're going to include a way to print out information about the number entered into the text input. Enter the following event handler below the existing functions: +
    input.onchange = function() {
    +  var num = input.value;
    +  if (isNaN(num)) {
    +    para.textContent = 'You need to enter a number!';
    +  } else {
    +    para.textContent = num + ' squared is ' + squared(num) + '. ' +
    +                       num + ' cubed is ' + cubed(num) + '. ' +
    +                       num + ' factorial is ' + factorial(num) + '.';
    +  }
    +}
    + +

    Here we are creating an onchange event handler that runs whenever the change event fires on the text input — that is, when a new value is entered into the text input, and submitted (enter a value then press tab for example). When this anonymous function runs, the existing value entered into the input is stored in the num variable.

    + +

    Next, we do a conditional test — if the entered value is not a number, we print an error message into the paragraph. The test looks at whether the expression isNaN(num) returns true. We use the isNaN() function to test whether the num value is not a number — if so, it returns true, and if not, false.

    + +

    If the test returns false, the num value is a number, so we print out a sentence inside the paragraph element stating what the square, cube, and factorial of the number are. The sentence calls the squared(), cubed(), and factorial() functions to get the required values.

    +
  6. +
  7. Save your code, load it in a browser, and try it out.
  8. +
+ +
+

Note: If you have trouble getting the example to work, feel free to check your code against the finished version on GitHub (see it running live also), or ask us for help.

+
+ +

At this point, we'd like you to have a go at writing out a couple of functions of your own and adding them to the library. How about the square or cube root of the number, or the circumference of a circle with a radius of length num?

+ +

This exercise has brought up a couple of important points besides being a study on how to use the return statement. In addition, we have:

+ + + +

Conclusion

+ +

So there we have it — functions are fun, very useful and, although there's a lot to talk about in regards to their syntax and functionality, fairly understandable given the right articles to study.

+ +

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Build_your_own_function","Learn/JavaScript/Building_blocks/Events", "Learn/JavaScript/Building_blocks")}}

+ +

In this module

+ + -- cgit v1.2.3-54-g00ecf