From 4f0e1ec1c2772904c033f747dc38a08223e8d661 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Thu, 15 Jul 2021 13:42:10 -0400 Subject: delete pages that were never translated from en-US (es, part 2) (#1550) --- .../javascript/asynchronous/async_await/index.html | 411 --------------- .../javascript/building_blocks/events/index.html | 579 --------------------- .../building_blocks/functions/index.html | 400 -------------- .../building_blocks/image_gallery/index.html | 145 ------ 4 files changed, 1535 deletions(-) delete mode 100644 files/es/learn/javascript/asynchronous/async_await/index.html delete mode 100644 files/es/learn/javascript/building_blocks/events/index.html delete mode 100644 files/es/learn/javascript/building_blocks/functions/index.html delete mode 100644 files/es/learn/javascript/building_blocks/image_gallery/index.html (limited to 'files/es/learn/javascript') diff --git a/files/es/learn/javascript/asynchronous/async_await/index.html b/files/es/learn/javascript/asynchronous/async_await/index.html deleted file mode 100644 index 3487b11664..0000000000 --- a/files/es/learn/javascript/asynchronous/async_await/index.html +++ /dev/null @@ -1,411 +0,0 @@ ---- -title: Haciendo la programación asíncrona más fácil con async y await -slug: Learn/JavaScript/Asynchronous/Async_await -translation_of: Learn/JavaScript/Asynchronous/Async_await ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}
- -

Las incorporaciones más recientes al lenguaje JavaScript, son las funciones async y la palabra clave await, parte de la edición ECMAScript 2017 (véase ECMAScript Next support in Mozilla). Estas características, básicamente, actúan como azúcar sintáctico, haciendo el código asíncrono fácil de escribir y leer más tarde. Hacen que el código asíncrono se parezca más al código síncrono de la vieja escuela, por lo que merece la pena aprenderlo. 

- -

Este artículo le da lo que usted necesita saber. 

- - - - - - - - - - - - -
Requisitos previos:Conocimientos básicos de informática, entender de manera razonable los fundamentos de JavaScript y entender el código asíncrono en general y las promesas. 
Objetivo:Entender las promesas y cómo usarlas
- -

Los fundamentos de async/await

- -

Hay dos partes a la hora de usar async/await en su código.

- -

La palabra clave async

- -

Primero tenemos la palabra clave "async", que se coloca delante de la declaración de una función, para convertirla en función "async"(asíncrona). Una función "async", es una función que sabe cómo esperar la posibilidad de que la palabra clave "await" sea utilizada para invocar código asíncrono. 

- -

Intenta escribir las siguientes líneas en la consola de tu navegador. 

- -
function hello() { return "Hello" };
-hello();
- -

La función returna "Hello" — nada especial, verdad?

- -

Pero, qué pasa si convertimos esto en una función async? Trata lo siguiente:

- -
async function hello() { return "Hello" };
-hello();
- -

Ah!. Ahora cuando invocamos la función, retorna una promesa(promise). Esta es una de las características particulares de las funciones async —  los valores que retornan están garantizados para ser convertidos en promesas.

- -

También puedes crear una expresión de función async, así:

- -
let hello = async function() { return "Hello" };
-hello();
- -

Y puedes utilizar funciones flecha(arrow functions):

- -
let hello = async () => { return "Hello" };
- -

Todos estos hacen básicamente lo mismo.

- -

Para realmente consumir el valor retornado cuando la promesa se cumple, ya que se está devolviendo una promesa, podemos utilizar un bloque then()

- -
hello().then((value) => console.log(value))
- -

o incluso sólo un shorthand como

- -
hello().then(console.log)
- -

Como vimos en el último artículo.

- -

La palabra clave async se añade a las funciones para decirles que devuelvan una promesa en lugar de devolver directamente el valor. Adicionamente, esto permite que las funciones síncronas eviten cualquier potencial sobrecarga que viene con correr con el soporte por usar async. Cuando una función es declarada async con sólo añadir la manipulación necesaria, el motor de JavaScript puede optimizar su programa por usted. Dulce!

- -

So the async keyword is added to functions to tell them to return a promise rather than directly returning the value. In addition, this lets synchronous functions avoid any potential overhead that comes with running with support for using await. By only adding the necessary handling when the function is declared async, the JavaScript engine can optimize your program for you. Sweet!

- -

La palabra clave await

- -

La ventaja real de las funciones asincronas aparecen cuando las combinas con la palabra clave await — en efecto, await solo trabaja dentro de las funciones async. Esta puede ser puesta frente a cualquier funcion async basada en una promesa para pausar tu codigo en esa linea hasta que se cumpla la promesa, entonces retorna el valor resultante. Mientras tanto, otro código que puede estar esperando una oportunidad para ejecutarse, puede hacerlo.

- -

Puedes usar await cuando llames cualquier funcion que retorna una Promesa, incluyendo funciones web API.

- -

Este es un ejemplo trivial:

- -
async function hello() {
-  return greeting = await Promise.resolve("Hello");
-};
-
-hello().then(alert);
- -

Por supuesto, el ejemplo anterior no es muy util, aunque este sirve para ilustrar la syntaxis. Vamos a ver un ejemplo real.

- -

Reescribiendo el código de las promesas con async/await

- -

Let's look back at a simple fetch example that we saw in the previous article:

- -
fetch('coffee.jpg')
-.then(response => {
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    return response.blob();
-  }
-})
-.then(myBlob => {
-  let objectURL = URL.createObjectURL(myBlob);
-  let image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-})
-.catch(e => {
-  console.log('There has been a problem with your fetch operation: ' + e.message);
-});
- -

By now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things:

- -
async function myFetch() {
-  let response = await fetch('coffee.jpg');
-
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    let myBlob = await response.blob();
-
-    let objectURL = URL.createObjectURL(myBlob);
-    let image = document.createElement('img');
-    image.src = objectURL;
-    document.body.appendChild(image);
-  }
-}
-
-myFetch()
-.catch(e => {
-  console.log('There has been a problem with your fetch operation: ' + e.message);
-});
- -

It makes code much simpler and easier to understand — no more .then() blocks everywhere!

- -

Since an async keyword turns a function into a promise, you could refactor your code to use a hybrid approach of promises and await, bringing the second half of the function out into a new block to make it more flexible:

- -
async function myFetch() {
-  let response = await fetch('coffee.jpg');
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    return await response.blob();
-  }
-}
-
-myFetch().then((blob) => {
-  let objectURL = URL.createObjectURL(blob);
-  let image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-}).catch(e => console.log(e));
- -

You can try typing in the example yourself, or running our live example (see also the source code).

- -

But how does it work?

- -

You'll note that we've wrapped the code inside a function, and we've included the async keyword before the function keyword. This is necessary — you have to create an async function to define a block of code in which you'll run your async code; as we said earlier, await only works inside of async functions.

- -

Inside the myFetch() function definition you can see that the code closely resembles the previous promise version, but there are some differences. Instead of needing to chain a .then() block on to the end of each promise-based method, you just need to add an await keyword before the method call, and then assign the result to a variable. The await keyword causes the JavaScript runtime to pause your code on this line, allowing other code to execute in the meantime, until the async function call has returned its result. Once that's complete, your code continues to execute starting on the next line. For example:

- -
let response = await fetch('coffee.jpg');
- -

The response returned by the fulfilled fetch() promise is assigned to the response variable when that response becomes available, and the parser pauses on this line until that occurs. Once the response is available, the parser moves to the next line, which creates a Blob out of it. This line also invokes an async promise-based method, so we use await here as well. When the result of operation returns, we return it out of the myFetch() function.

- -

This means that when we call the myFetch() function, it returns a promise, so we can chain a .then() onto the end of it inside which we handle displaying the blob onscreen.

- -

You are probably already thinking "this is really cool!", and you are right — fewer .then() blocks to wrap around code, and it mostly just looks like synchronous code, so it is really intuitive.

- -

Adding error handling

- -

And if you want to add error handling, you've got a couple of options.

- -

You can use a synchronous try...catch structure with async/await. This example expands on the first version of the code we showed above:

- -
async function myFetch() {
-  try {
-    let response = await fetch('coffee.jpg');
-
-    if (!response.ok) {
-      throw new Error(`HTTP error! status: ${response.status}`);
-    } else {
-      let myBlob = await response.blob();
-      let objectURL = URL.createObjectURL(myBlob);
-      let image = document.createElement('img');
-      image.src = objectURL;
-      document.body.appendChild(image);
-    }
-  } catch(e) {
-    console.log(e);
-  }
-}
-
-myFetch();
- -

The catch() {} block is passed an error object, which we've called e; we can now log that to the console, and it will give us a detailed error message showing where in the code the error was thrown.

- -

If you wanted to use the second (refactored) version of the code that we showed above, you would be better off just continuing the hybrid approach and chaining a .catch() block onto the end of the .then() call, like this:

- -
async function myFetch() {
-  let response = await fetch('coffee.jpg');
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    return await response.blob();
-  }
-}
-
-myFetch().then((blob) => {
-  let objectURL = URL.createObjectURL(blob);
-  let image = document.createElement('img');
-  image.src = objectURL;
-  document.body.appendChild(image);
-})
-.catch((e) =>
-  console.log(e)
-);
- -

This is because the .catch() block will catch errors occurring in both the async function call and the promise chain. If you used the try/catch block here, you might still get unhandled errors in the myFetch() function when it's called.

- -

You can find both of these examples on GitHub:

- - - -

Awaiting a Promise.all()

- -

async/await is built on top of promises, so it's compatible with all the features offered by promises. This includes Promise.all() — you can quite happily await a Promise.all() call to get all the results returned into a variable in a way that looks like simple synchronous code. Again, let's return to an example we saw in our previous article. Keep it open in a separate tab so you can compare and contrast with the new version shown below.

- -

Converting this to async/await (see live demo and source code), this now looks like so:

- -
async function fetchAndDecode(url, type) {
-  let response = await fetch(url);
-
-  let content;
-
-  if (!response.ok) {
-    throw new Error(`HTTP error! status: ${response.status}`);
-  } else {
-    if(type === 'blob') {
-      content = await response.blob();
-    } else if(type === 'text') {
-      content = await response.text();
-    }
-
-    return content;
-  }
-
-}
-
-async function displayContent() {
-  let coffee = fetchAndDecode('coffee.jpg', 'blob');
-  let tea = fetchAndDecode('tea.jpg', 'blob');
-  let description = fetchAndDecode('description.txt', 'text');
-
-  let values = await Promise.all([coffee, tea, description]);
-
-  let objectURL1 = URL.createObjectURL(values[0]);
-  let objectURL2 = URL.createObjectURL(values[1]);
-  let descText = values[2];
-
-  let image1 = document.createElement('img');
-  let image2 = document.createElement('img');
-  image1.src = objectURL1;
-  image2.src = objectURL2;
-  document.body.appendChild(image1);
-  document.body.appendChild(image2);
-
-  let para = document.createElement('p');
-  para.textContent = descText;
-  document.body.appendChild(para);
-}
-
-displayContent()
-.catch((e) =>
-  console.log(e)
-);
- -

You'll see that the fetchAndDecode() function has been converted easily into an async function with just a few changes. See the Promise.all() line:

- -
let values = await Promise.all([coffee, tea, description]);
- -

By using await here we are able to get all the results of the three promises returned into the values array, when they are all available, in a way that looks very much like sync code. We've had to wrap all the code in a new async function, displayContent(), and we've not reduced the code by a lot of lines, but being able to move the bulk of the code out of the .then() block provides a nice, useful simplification, leaving us with a much more readable program.

- -

For error handling, we've included a .catch() block on our displayContent() call; this will handle errors ocurring in both functions.

- -
-

Note: It is also possible to use a sync finally block within an async function, in place of a .finally() async block, to show a final report on how the operation went — you can see this in action in our live example (see also the source code).

-
- -

The downsides of async/await

- -

Async/await is really useful to know about, but there are a couple of downsides to consider.

- -

Async/await makes your code look synchronous, and in a way it makes it behave more synchronously. The await keyword blocks execution of all the code that follows until the promise fulfills, exactly as it would with a synchronous operation. It does allow other tasks to continue to run in the meantime, but your own code is blocked.

- -

This means that your code could be slowed down by a significant number of awaited promises happening straight after one another. Each await will wait for the previous one to finish, whereas actually what you want is for the promises to begin processing simultaneously, like they would do if we weren't using async/await.

- -

There is a pattern that can mitigate this problem — setting off all the promise processes by storing the Promise objects in variables, and then awaiting them all afterwards. Let's have a look at some examples that prove the concept.

- -

We've got two examples available — slow-async-await.html (see source code) and fast-async-await.html (see source code). Both of them start off with a custom promise function that fakes an async process with a setTimeout() call:

- -
function timeoutPromise(interval) {
-  return new Promise((resolve, reject) => {
-    setTimeout(function(){
-      resolve("done");
-    }, interval);
-  });
-};
- -

Then each one includes a timeTest() async function that awaits three timeoutPromise() calls:

- -
async function timeTest() {
-  ...
-}
- -

Each one ends by recording a start time, seeing how long the timeTest() promise takes to fulfill, then recording an end time and reporting how long the operation took in total:

- -
let startTime = Date.now();
-timeTest().then(() => {
-  let finishTime = Date.now();
-  let timeTaken = finishTime - startTime;
-  alert("Time taken in milliseconds: " + timeTaken);
-})
- -

It is the timeTest() function that differs in each case.

- -

In the slow-async-await.html example, timeTest() looks like this:

- -
async function timeTest() {
-  await timeoutPromise(3000);
-  await timeoutPromise(3000);
-  await timeoutPromise(3000);
-}
- -

Here we simply await all three timeoutPromise() calls directly, making each one alert for 3 seconds. Each subsequent one is forced to wait until the last one finished — if you run the first example, you'll see the alert box reporting a total run time of around 9 seconds.

- -

In the fast-async-await.html example, timeTest() looks like this:

- -
async function timeTest() {
-  const timeoutPromise1 = timeoutPromise(3000);
-  const timeoutPromise2 = timeoutPromise(3000);
-  const timeoutPromise3 = timeoutPromise(3000);
-
-  await timeoutPromise1;
-  await timeoutPromise2;
-  await timeoutPromise3;
-}
- -

Here we store the three Promise objects in variables, which has the effect of setting off their associated processes all running simultaneously.

- -

Next, we await their results — because the promises all started processing at essentially the same time, the promises will all fulfill at the same time; when you run the second example, you'll see the alert box reporting a total run time of just over 3 seconds!

- -

You'll have to test your code carefully, and bear this in mind if performance starts to suffer.

- -

Another minor inconvenience is that you have to wrap your awaited promises inside an async function.

- -

Async/await class methods

- -

As a final note before we move on, you can even add async in front of class/object methods to make them return promises, and await promises inside them. Take a look at the ES class code we saw in our object-oriented JavaScript article, and then look at our modified version with an async method:

- -
class Person {
-  constructor(first, last, age, gender, interests) {
-    this.name = {
-      first,
-      last
-    };
-    this.age = age;
-    this.gender = gender;
-    this.interests = interests;
-  }
-
-  async greeting() {
-    return await Promise.resolve(`Hi! I'm ${this.name.first}`);
-  };
-
-  farewell() {
-    console.log(`${this.name.first} has left the building. Bye for now!`);
-  };
-}
-
-let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
- -

The first class method could now be used something like this:

- -
han.greeting().then(console.log);
- -

Browser support

- -

One consideration when deciding whether to use async/await is support for older browsers. They are available in modern versions of most browsers, the same as promises; the main support problems come with Internet Explorer and Opera Mini.

- -

If you want to use async/await but are concerned about older browser support, you could consider using the BabelJS library — this allows you to write your applications using the latest JavaScript and let Babel figure out what changes if any are needed for your user’s browsers. On encountering a browser that does not support async/await, Babel's polyfill can automatically provide fallbacks that work in older browsers.

- -

Conclusion

- -

And there you have it — async/await provide a nice, simplified way to write async code that is simpler to read and maintain. Even with browser support being more limited than other async code mechanisms at the time of writing, it is well worth learning and considering for use, both for now and in the future.

- -

{{PreviousMenuNext("Learn/JavaScript/Asynchronous/Promises", "Learn/JavaScript/Asynchronous/Choosing_the_right_approach", "Learn/JavaScript/Asynchronous")}}

- -

In this module

- - diff --git a/files/es/learn/javascript/building_blocks/events/index.html b/files/es/learn/javascript/building_blocks/events/index.html deleted file mode 100644 index 5fc7ee8df5..0000000000 --- a/files/es/learn/javascript/building_blocks/events/index.html +++ /dev/null @@ -1,579 +0,0 @@ ---- -title: Introducción a eventos -slug: Learn/JavaScript/Building_blocks/Events -translation_of: Learn/JavaScript/Building_blocks/Events -original_slug: Learn/JavaScript/Building_blocks/Eventos ---- -
{{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 deleted file mode 100644 index d05ae34969..0000000000 --- a/files/es/learn/javascript/building_blocks/functions/index.html +++ /dev/null @@ -1,400 +0,0 @@ ---- -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/image_gallery/index.html b/files/es/learn/javascript/building_blocks/image_gallery/index.html deleted file mode 100644 index a4bad1842e..0000000000 --- a/files/es/learn/javascript/building_blocks/image_gallery/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Galería de imágenes -slug: Learn/JavaScript/Building_blocks/Image_gallery -translation_of: Learn/JavaScript/Building_blocks/Image_gallery -original_slug: Learn/JavaScript/Building_blocks/Galeria_de_imagenes ---- -
{{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

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