Web Development - JavaScript Conditions
JavaScript Conditions and Loops
Programs often need to make decisions or repeat actions. JavaScript uses conditions to decide what code to run and loops to repeat tasks automatically.
Conditions
Conditions let your program choose what to do based on whether something is true or false.
A basic condition uses the if statement.
You can add else or else if to handle other outcomes.
Syntax
if (condition) {
// code runs if condition is true
} else if (anotherCondition) {
// code runs if the first condition is false and this one is true
} else {
// code runs if none of the conditions are true
}
Each condition must return true or false.
JavaScript runs only the first block whose condition is true.
The if Statement
Use if to run a block of code when a condition is true.
Example
Simple if statement:
let age = 18;
let message;
if (age >= 18) {
message = "You can vote!";
}
Try it Yourself »
if...else
Use else to run code when the condition is false.
Example
Check login status:
let loggedIn = false;
let message;
if (loggedIn) {
message = "Welcome back!";
} else {
message = "Please log in.";
}
Try it Yourself »
if...else if...else
Use else if to test several conditions in order.
Example
Check a temperature:
let temp = 25;
let message;
if (temp > 30) {
message = "Hot";
} else if (temp > 20) {
message = "Warm";
} else {
message = "Cold";
}
Try it Yourself »
Switch Statement
Use switch when you want to compare one value to many possible matches.
Example
Switch between color options:
let color = "green";
let message;
switch (color) {
case "red":
message = "Stop";
break;
case "yellow":
message = "Caution";
break;
case "green":
message = "Go";
break;
default:
message = "Invalid color";
}
Try it Yourself »
Note: Always use break to stop the code from continuing to the next case.
Logical Operators in Conditions
You can combine multiple conditions using logical operators:
&&(AND) - both must be true||(OR) - at least one must be true!(NOT) - reverses true/false
Example
Check if the weather is good for to swim outside:
let isSunny = true;
let isWarm = true;
let message;
if (isSunny && isWarm) {
message = "Perfect day for a swim outside!";
} else {
message = "Maybe stay indoors.";
}
Try it Yourself »
Best Practices
- Use
ifstatements to handle conditions. - Use
switchfor multiple possible values. - Store your results in variables - it makes your code easier to test and display later.
Next, you'll learn about JavaScript Loops - how to repeat actions automatically.