3. Conditionals

Conditionals let us make decisions, creating branches in the logic of the software we're building: under what conditions should I run these instructions? What do I do if my requirements aren't met?

if (condition) {
// Instructions that will run if the previous condition is met
}

If you only have one instruction, it can all go on the same line without braces {}.

if (condition) // Instruction;

Types of conditionals

Symbol Explanation Example
:-------------: :-------------: :-----:
> is greater than if (1 > 0)
< is less than if (1 < 0)
&& and if (1 > 0 && 67 > 0)
|| or if (1 > 10 || 67 > 0)
== is equal in value if ("3" == 3)
=== is equal in value and type if ("3" === "3")
! not if (!(1 > 0))
!= is not equal if ("Doctor" != "Who")
!== is not equal in value or type if ("Doctor" !== "Who")
>= is greater than or equal to if (10 >= 10)
<= is less than or equal to if (10 <= 20)
true True if (true)
false False if (false)

A simple conditional could be:

const nombre = "Victoria";

if (nombre == "Victoria") {
console.log("Hola Victoria");
}

// Hola Victoria

We can chain several conditions with &&.

if (10 > 2 && true && "HBO" != "Netflix") {
console.log("Entro seguro");
}

// Entro seguro

All the conditions must be met for it to enter.

If you want, you can also leave it on a single line.

if (10 > 2 && true && "HBO" != "Netflix") console.log("Entro seguro");

// Entro seguro

If you want it to enter when only one of the conditions is met, you can use ||.

miStreaming = "HBO";

if (miStreaming === "HBO" || miStreaming === "Netflix") {
console.log("Esta noche vemos una serie");
}

// Esta noche vemos una serie

else

Lets us perform other actions if the condition isn't met.

if (condition) {
...
} else {
...
}
if (10 < 9) {
console.log("Entro seguro");
} else {
console.log("No entro");
}

// No entro

else if

It's possible to have several conditionals, although only one of them will run.

if (condition) {
...
} else if (condition) {
...
} else {
...
}
const nombre = "Juan";

if (nombre == "Victoria") {
console.log("Hola Victoria");
} else if (nombre == "Juan") {
console.log("Hola Juan");
} else {
console.log("Hola desconocido");
}

// Hola Juan

Ternary operator

It lets you run an if with an else in a single instruction. If you're just starting out, I don't recommend using it, but don't forget about it.

condition ? "Value if true" : "Value if false";
5 > 10 ? "Es verdad" : "Es mentira";

// Es mentira

It has a very interesting quirk: it returns the value.

In the following example I store in saludo a text that depends on whether the condition is met or not.

const nombre = "Javi";

const saludo = nombre == "María" ? "Hola María" : "Hola desconocido";

console.log(saludo);
// Hola desconocido

Switch

It behaves like a condition whose value is matched across every case.

switch (variable) {
    case 0:
        ...
        break;
    case 1:
        ...
        break;
    case 2:
        ...
        break;
    default:
        ...
        break;
}

Let's see an example.

const edad = 65;

switch (edad) {
    case 0:
        console.log("Recién nacio");
        break;
    case 18:
        console.log("Ya es un hombre");
        break;
    case 65:
        console.log("Recién jubilado");
        break;
    default:
        console.log("¿Aún estas vivo?");
        break;
}

// Recién jubilado

Nullish coalescing operator

At certain moments we'll come across null values. To avoid problems, the best approach is to provide a default value. JavaScript gives us a tool that returns the right-hand side if the left-hand side is null or undefined.

const variable1 = "Agua" || "Alternativa"
// "Agua"

const variable2 = null || "Alternativa"
// "Alternativa"

Nowadays it's recommended to use ??, a spiritual evolution of ||, since it can return false negatives with "" or 0 in certain situations.

Let's see an example. Everything in the following code will return Alternativa:

0 || "Alternativa"
"" || "Alternativa"
false || "Alternativa"
undefined || "Alternativa"
null || "Alternativa"

While if we use ??:

0 ?? "Alternativa" // 0
"" ?? "Alternativa" // ""
false ?? "Alternativa" // false
undefined ?? "Alternativa" // "Alternativa"
null ?? "Alternativa" // "Alternativa"

Definitely more reliable.

Optional chaining

If I try to access a value that doesn't exist, we'll get undefined.

const perfil = {
    nombre: "Miguel",
    edad: 45,
    activo: true,
    direccion: {
        calle: "falsa",
        numero: 123
    }
};

perfil.edad // 45
perfil.nombre // "Miguel"
perfil.apellidos // undefined

There's no issue if we're working with a single level of depth. But when we want to get a value further down, and it doesn't exist, it will throw an error that stops execution.

perfil.direccion.calle // "falsa"
perfil.comentarios.nombre // Uncaught TypeError

To fix this we can catch the error and handle it, or return undefined. To do this we can use a question mark to mark it as optional.

perfil.direccion.calle // "falsa"
perfil.comentarios?.nombre // undefined

And if we combine it with the nullish coalescing operator (??), we can even get a default value.

perfil.direccion.calle ?? "Sin calle" // "falsa"
perfil.comentarios?.nombre ?? "Sin comentarios" // "Sin comentarios"
Activity 1

Run

prompt('Tengo agujas pero no sé coser, tengo números pero no sé leer, las horas te doy, ¿Sabes quién soy?')

Store the answer in a variable. Print to the console whether it got it right.

By the way, the answer to the riddle is: The clock.

Activity 2

Automatic nightclub bouncer

  • Ask for the year of birth.
  • Calculate the age.
  • If they're of legal age, tell them they can go inside.
  • If they're underage, throw them out.

Nightmare level 👹

Also ask for the day and month of birth to know whether they've had their birthday this year.

Hint: On average, 1 year has 31556952000 ms

Activity 3

Starting from the following constants...

const animal = '...';
const sexo = '...';
const hijos = ...;

The following sentence is generated: The {'father' or 'mother' based on sex} {animal} has {hijos} children.

For example:

const animal = 'elefante';
const sexo = 'mujer';
const hijos = 3;

We get: The mother elephant has 3 children.

Now change the variables to the following combinations and generate the appropriate sentences using conditionals.

const animal = 'aguila';
const sexo = 'hombre';
const hijos = 7;
const animal = 'ballena';
const sexo = 'mujer';
const hijos = 1;
const animal = 'tigre';
const sexo = 'hombre';
const hijos = 0;

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.