4. Functions

There comes a moment, in every development, when you end up reusing the same code over and over. It might be a couple of lines or hundreds of them. From an organizational standpoint it's more practical to create a group that can be invoked than to keep copying and pasting in different places. Plus, it's faster to modify once than several times. This feature is called: function.

Simple

The structure is as follows.

function alias() {
// code
}

And to run it we'll use alias with parentheses.

alias();

An example.

function saludo() {
console.log('Hello everyone');
}

saludo();
// Hello everyone

Name functions with nouns: perfilDeUsuario(), ultimaPagina(), columnasImpares()...

Arguments

It's possible to customize a function's instructions with arguments and variables when it's invoked.

We can see how it works with a single argument.

function saludo(nombre) {
    console.log(`Hello ${nombre}`);
}

saludo('Luis');

And if we needed to add more arguments, we separate them with commas.

function saludo(nombre, localidad) {
    console.log(`Hello ${nombre} from ${localidad}`);
}

saludo('Luis', 'Valencia');
// Hello Luis from Valencia

Default arguments

It can happen that an argument is optional, or that it has a fixed value if it isn't declared.

function saludaA(nombre='everyone') {
    console.log(`Hello ${nombre}`);
}

saludaA();
// Hello everyone
saludaA('Luis');
// Hello Luis

With an array of arguments

What happens if we don't want to restrict the number of arguments? In other words: we want to be able to receive infinite arguments. That's possible, although it will create an array for us (we'll see this later on).

function diasLibres(...dias) {
    console.log(dias);
}

diasLibres('Monday', 'Thursday', 'Sunday');
// ['Monday', 'Thursday', 'Sunday']

Return

The functions we've dealt with so far are black boxes: they run some code but we don't get a response back. If we want to return a variable we'll use return.

In this example a string is produced, but it's lost since it's not captured.

function saluda() {
    return 'Hello everyone';
}

saluda();
// Hello everyone

Now it will be stored in a constant and then printed.

const texto = saluda();

console.log(texto);
// Hello everyone

Another example, a bit more advanced and practical, could be a small function that helps us calculate how old a person is.

function calcularEdad(anyo) {
    return new Date().getFullYear() - anyo;
}

const nombre = "Bob";
const anyoNacimiento = 2000;
const edad = calcularEdad(anyoNacimiento)


console.log(`${nombre} was born in ${anyoNacimiento} and is ${edad} years old.`);
// Bob was born in 2000 and is 22 years old.

You've already experienced this mechanism firsthand without knowing it when you used .toUpperCase(), using a function as if it were a variable, or in other words, pure functions.

{: .advice } You can go deeper into the topic by learning about functional programming with a brief introduction in JavaScript, one of the three fundamental paradigms in the programming world.

Anonymous

Just like a function can return a string, integer, float or boolean... it can also return a function. You just need to omit its name.

// I store the function in the "miFuncion" variable so I don't lose it.
const miFuncion = function() {
    console.log("I'm anonymous");
};

I run it.

miFuncion();

// I'm anonymous

Don't worry if you don't quite see its use yet, you'll declare it alongside other more complex functions. Being able to recognize its syntax will be enough for now.

Recursion

You've seen that a function can call another function. And can it call itself? It's possible, and it's called recursion.

function nombre() {
    return nombre();
}

It's useful when we want to call the function again until certain requirements are met, or when we want to perform a calculation recursively.

In the following example I keep asking for a number until the user guesses it, meeting the condition.

function adivinarNumero() {
    // Variables
    const numeroAdivinar = 4;
    const respuesta = prompt('From 1 to 5, what number am I thinking of?');
    // Logic
    if (respuesta == numeroAdivinar) {
        alert("You guessed it!")
        return true;
    }
    return adivinarNumero();
}

adivinarNumero();

Another common, and more advanced, use is for performing calculations.

function sumarNumerosNaturales(n) {
    return n > 0 ? n + sumarNumerosNaturales(n - 1) : n;
}

sumarNumerosNaturales(8);
// 36

function generar_secuencia_fibonacci(longitud, secuencia=[0, 1]) {
    return secuencia.length < longitud ? generar_secuencia_fibonacci(longitud, secuencia.concat(secuencia.at(-1) + secuencia.at(-2))) : secuencia;
}

generar_secuencia_fibonacci(7);
// [0, 1, 1, 2, 3, 5, 8]

Special functions

alert()

Shows a native warning modal.

alert('Team hacked');

prompt()

Shows a modal where the user can enter text.

const respuesta = prompt('What is your favorite color?');
// Answer: Orange

console.log(respuesta);
// Orange

setTimeout()

Runs a function with a delay. Its argument is an anonymous function, as we've seen before.

In the example it will fire after 2s.

const miTimeout = setTimeout(function() {
    alert('Accept our cookies?');
}, 2000);

setInterval()

Runs a function every so often, indefinitely unless you stop it. It needs an anonymous function.

In the example it will fire every 3s.

const miIntervalo = setInterval(function() {
    alert('Deleting a random photo of yours');
}, 3000);

Why do we store the interval in a variable? In case we want to stop it in the future. We have another specialized function called clearInterval.

clearInterval(miIntervalo);

Comment blocks

Code reflects health if it has good comments, it increases its life expectancy and speaks very well of the author. That's why it's important to leave a good instruction manual on how to use each function.

/**
 * Returns the sum of the arguments
 *
 * @param {number} num1 First number to add.
 * @param {number} num2 Second number to add.
 * @return {number} result of the sum.
 */
function sumar(num1, num2) {
    return num1 + num2;
}

Avoid comments about "how the code works" in favor of "what it returns".

Activity 1

Create a function that adds 2 numbers.

Nightmare level 👹

Create another function that receives a price and prints it with an added tax (21%).

Activity 2
  1. Create a function called alturaFormateada.
  2. Add an input argument called centimetros.
  3. When invoked with a number, for example 178, it should print 1,78 m.

Nightmare level 👹

Force it to always have 2 decimals.

Activity 3

Show the time in the console with its minutes and seconds: 16:10:32. It must update every second.

Activity 4

3.5 seconds after the website loads, show a banner suggesting the visitor subscribe.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.