JavaScript Decision Making
Decision making is a fundamental aspect of programming that allows you to control the flow of your code by making choices based on conditions. In JavaScript, you can use various constructs to implement decision-making logic. In this tutorial, we'll explore how to make decisions in JavaScript.
The if Statement
The if statement is one of the most basic decision-making constructs in JavaScript. It allows you to execute a block of code only if a specified condition is true.
if (condition) {
// Code to be executed if the condition is true
}
For example, if you want to check if a user is older than 18:
let age = 20;
if (age > 18) {
console.log("You are an adult.");
}
The if...else Statement
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
For example, to check if a user is eligible to vote:
The if...else if...else Statement
The if...else if...else statement allows you to test multiple conditions in sequence and execute the code block associated with the first true condition.
For example, classifying exam grades:
Ternary Operator
The ternary operator (condition ? expression1 : expression2) provides a concise way to make decisions and assign values based on a condition.
The switch Statement
The switch statement is used when you have a single expression to be compared to multiple possible case values. It provides an efficient way to perform different actions based on the value of the expression.
For example, displaying the day of the week: