How to make a choice JavaScript
Learn how to make a Javascript selection with an example: see how to use functions and variables to select from multiple options.
Making a Choice in JavaScript
Making a choice in JavaScript is a common task that needs to be done in web development. It's a straightforward process and requires two basic steps.
The first step is to define the choices. This can be done with a simple array of strings or numbers, like so:
var choices = ["choice1", "choice2", "choice3"];
The second step is to write a function that takes in a choice and returns a result. This can be done with a switch statement, like so:
function makeChoice(choice) {
switch(choice) {
case "choice1":
return "You chose Choice 1!";
case "choice2":
return "You chose Choice 2!";
case "choice3":
return "You chose Choice 3!";
default:
return "Invalid choice!";
}
}
Now that we have our choices defined and our function to process them, we can make a choice. We could do this with a simple if statement, like so:
var choice = "choice1";
if (choices.indexOf(choice) > -1) {
var result = makeChoice(choice);
console.log(result); // You chose Choice 1!
}
Or we could do it with a prompt, like so:
var choice = prompt("Please enter your choice");
if (choices.indexOf(choice) > -1) {
var result = makeChoice(choice);
console.log(result); // You chose Choice 1!
}
In this way, we can easily make a choice in JavaScript and process the result with a simple function.