Functions · Funciones
Functions
- A function is a named block of code you can run again and again.
function name(params) { ... return value; }. Theparamsare the inputs.returnhands a value back to whoever called the function.
Funciones
- Una función es un bloque de código con nombre que puedes ejecutar una y otra vez.
function name(params) { ... return value; }. Losparamsson las entradas.returndevuelve un valor a quien haya llamado a la función.
function square(n) {
return n * n;
}
console.log(square(6)); // → 36
Functions that just do something
- A function can do something (like print) instead of returning a value.
- Call it by writing its name and brackets:
greet("Ada").
Funciones que simplemente hacen algo
- Una función puede hacer algo (como imprimir) en lugar de devolver un valor.
- Llámala escribiendo su nombre y los corchetes:
greet("Ada").
function greet(name) {
console.log("Hi, " + name); // → Hi, Ada
}
greet("Ada");
Call and return · Llamada y retorno
Each call runs the body with its own input, then return hands a value back. · Cada llamada ejecuta el cuerpo con su propia entrada, luego return devuelve un valor.
Watch out
- The names in the brackets (
n,name) are parameters — they only exist inside the function. - A function with no
returngives backundefined. Addreturnwhen you want an answer out.
Ten cuidado
- Los nombres dentro de los paréntesis (
n,name) son parámetros: solo existen dentro de la función. - Una función sin
returndevuelveundefined. Añadereturncuando quieras obtener un resultado.
Common mistakes
returngives back a value; without it a function returnsundefined.- Call the function with
().
Errores comunes
returndevuelve un valor; sin él, una función devuelveundefined.- Llama a la función con
().
Now you try
- Write each function — it is called for you in the check.
- Press Check answer to test it.
Ahora te toca a ti
- Escribe cada función; esta se llamará automáticamente en la comprobación.
- Pulsa Check answer para probarla.
Write a function double(n) that returns · retornos n times 2. · Escribe una función double(n) que retorne n veces 2.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write a function add(a, b) that returns a + b. · Escribe una función add(a, b) que retorne a + b.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write a function greet(name) that logs Hi, then the name, then call greet("Ada"). Output should be Hi, Ada. · Escribe una función greet(name) que imprima Hi, seguido del nombre, luego llama a greet("Ada"). La salida debe ser Hi, Ada.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.