Skip to main content

Exercise 17: Options Menu with a Switch Statement in JavaScript

Implement an interactive menu in JavaScript using the switch statement structure. Learn to handle multiple conditions efficiently.

The main goal is to learn how to use the switch statement structure.switchto perform different actions depending on the selected option.

Activity

  1. Display an options menu in the console:

1: View welcome message ...2: View farewell message

(This appears to be a separate, unrelated message:)3: View help message

  1. Useswitchto display the message corresponding to the selected option.

  2. If the user chooses a different option, it displays "Invalid option".

Solution

Step 1: Create the index.html file

HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Menú de Opciones con switch</title>
</head>
<body>
<h1>Ejercicio 17: Menú de Opciones con switch</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>

Step 2: Write the code in script.js

JavaScript
let opcion = prompt(
"Selecciona una opción:\n1. Bienvenida\n2. Despedida\n3. Ayuda",
);

switch (opcion) {
case "1":
console.log("¡Bienvenido al sistema!");
break;
case "2":
console.log("Gracias por visitarnos. ¡Adiós!");
break;
case "3":
console.log("Para ayuda, visita nuestra página web.");
break;
default:
console.log("Opción no válida.");
}
info

🔎Check the sectionControl instructions in JavaScriptwhere you will find more information on this topic.