Conditional Statements in JavaScript: A Complete Guide
#Conditional Statements in JavaScript: A Complete Guide
Conditional statements are used in JavaScript to make decisions based on certain conditions. They allow you to control the flow of your code and execute different blocks of code depending on whether conditions are true or false.
In this tutorial, we’ll explore the main types of conditional statements in JavaScript with examples.
if
StatementExecutes a block of code if a specified condition is true.
if (condition) {
// code to run if condition is true
}
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
if...else
StatementExecutes one block of code if the condition is true, and another if it's false.
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
let isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
if...else if...else
StatementAllows you to check multiple conditions.
if (condition1) {
// code block 1
} else if (condition2) {
// code block 2
} else {
// code block 3
}
let score = 85;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 80) {
console.log("Grade B");
} else {
console.log("Grade C or lower");
}
A shorthand for if...else
. It returns one of two values based on a condition.
condition ? valueIfTrue : valueIfFalse;
let age = 20;
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message); // Adult
switch
Statement
A cleaner alternative to many else if
blocks. It evaluates an expression and matches it with a case
.
switch(expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default code block
}
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("Banana is yellow.");
break;
case "apple":
console.log("Apple is red.");
break;
default:
console.log("Unknown fruit.");
}
✅ Use if
for simple conditions.
✅ Use switch
for multiple possible values of the same variable.
✅ Avoid deeply nested if...else
for better readability.
✅ Use ternary operator for short, simple decisions.
Conditional statements are a core part of programming logic in JavaScript. They enable your code to make decisions, control flow, and adapt to different situations. By mastering if
, else
, switch
, and the ternary operator, you'll be able to write more dynamic and responsive applications.