07 - Switch

Estructura inicial

En nuestra carpeta de proyecto crearemos la siguiente estructura:

/
├── js/
│   └── 07-switch.js
└── index.html

Y un código sencillo para nuestro HTML:

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/07-switch.js"></script>
    <title>07 - Switch</title>
</head>
<body>
    <h1>Temario de JavaScript</h1>
</body>
</html>

Estructura de un Switch

switch(variable) {
    case valor1:
        //Código a ejecutar si variable == valor1
        break
    case valor2:
        //Código a ejecutar si variable == valor2
        break
    case valor3:
        //Código a ejecutar si variable == valor3
        break
    default:
        //Código a ejecutar si no se cumple ninguna de las condiciones anteriores
        break
}

Ejemplo de Switch

let idioma = "en"

switch(idioma) {
    case "es":
        console.log("Hola")
        break
    case "pt":
        console.log("Ola")
        break
    case "jp":
        console.log("こんにちは")
        break
    default:
        console.log("Hello")
        break
}
//Hello

Al no cumplirse ninguna de las condiciones, va al valor por defecto