Learn how to control the flow of your JavaScript programs using conditional statements, including if, else if, else, and the ternary operator. Understand truthy and falsy values to write efficient code.
In the world of programming, making decisions is crucial. Conditional statements in JavaScript allow us to control the flow of our programs by executing different blocks of code based on certain conditions. This section will guide you through the basics of conditional statements, including if
, else if
, else
, and the ternary operator. We’ll also explore truthy and falsy values, which are essential for understanding how conditions are evaluated in JavaScript.
Conditional statements enable your program to make decisions and execute specific code blocks based on whether a condition is true
or false
. This decision-making ability is fundamental for creating dynamic and interactive web pages.
if
StatementThe if
statement is the most basic form of conditional statement. It allows you to execute a block of code only if a specified condition evaluates to true
.
Syntax:
if (condition) {
// Code to execute if the condition is true
}
Example:
let temperature = 30;
if (temperature > 25) {
console.log("It's a hot day!");
}
In this example, the message “It’s a hot day!” will be logged to the console only if the temperature
is greater than 25.
else
StatementThe else
statement can be used in conjunction with the if
statement to execute a block of code if the condition is false
.
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
Example:
let temperature = 20;
if (temperature > 25) {
console.log("It's a hot day!");
} else {
console.log("It's a cool day!");
}
Here, “It’s a cool day!” will be logged to the console because the condition temperature > 25
is false
.
else if
StatementWhen you have multiple conditions to evaluate, you can use the else if
statement. This allows you to check additional conditions if the previous ones are false
.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the conditions are true
}
Example:
let temperature = 15;
if (temperature > 25) {
console.log("It's a hot day!");
} else if (temperature > 15) {
console.log("It's a warm day!");
} else {
console.log("It's a cold day!");
}
In this case, “It’s a cold day!” will be logged because both conditions temperature > 25
and temperature > 15
are false
.
In JavaScript, conditions are evaluated based on truthy and falsy values. Understanding these concepts is essential for writing effective conditional statements.
A falsy value is a value that translates to false
when evaluated in a Boolean context. The following values are considered falsy in JavaScript:
false
0
""
(an empty string)null
undefined
NaN
(Not-a-Number)Example:
let value = 0;
if (value) {
console.log("This is truthy!");
} else {
console.log("This is falsy!");
}
Since 0
is a falsy value, “This is falsy!” will be logged to the console.
A truthy value is any value that is not falsy. This means that most values in JavaScript are truthy, including:
1
, -1
)"hello"
)Example:
let value = "hello";
if (value) {
console.log("This is truthy!");
} else {
console.log("This is falsy!");
}
Since "hello"
is a truthy value, “This is truthy!” will be logged to the console.
The ternary operator is a shorthand way of writing an if...else
statement. It is a concise way to evaluate a condition and return one of two values based on whether the condition is true
or false
.
Syntax:
condition ? expressionIfTrue : expressionIfFalse;
Example:
let temperature = 30;
let message = temperature > 25 ? "It's a hot day!" : "It's a cool day!";
console.log(message);
In this example, the ternary operator checks if temperature > 25
. If true
, it assigns “It’s a hot day!” to message
; otherwise, it assigns “It’s a cool day!”.
Now that we’ve covered the basics of conditional statements, let’s apply this knowledge to solve simple problems.
Let’s write a program that checks if a person is eligible to vote.
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}
In this example, the program checks if age
is greater than or equal to 18. If true
, it logs “You are eligible to vote.”; otherwise, it logs “You are not eligible to vote.”
Let’s create a simple grading system that assigns a letter grade based on a numerical score.
let score = 85;
let grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else if (score >= 60) {
grade = "D";
} else {
grade = "F";
}
console.log(`Your grade is: ${grade}`);
In this example, the program assigns a letter grade based on the value of score
. It uses multiple else if
statements to check different ranges of scores.
Now it’s your turn! Try modifying the examples above to see how different conditions affect the output. Here are a few suggestions:
temperature
value in the first example to see how the output changes.age
value to test different eligibility scenarios.score
values to see how the grading system assigns grades.To better understand how conditional statements work, let’s visualize the flow of a simple if...else if...else
structure using a flowchart.
flowchart TD A[Start] --> B{Condition 1} B -- Yes --> C[Execute Block 1] B -- No --> D{Condition 2} D -- Yes --> E[Execute Block 2] D -- No --> F[Execute Block 3] C --> G[End] E --> G F --> G
Diagram Description: This flowchart represents a basic if...else if...else
structure. The program checks Condition 1
. If true
, it executes Block 1
and ends. If false
, it checks Condition 2
. If Condition 2
is true
, it executes Block 2
and ends. If both conditions are false
, it executes Block 3
and ends.
To deepen your understanding of conditional statements in JavaScript, consider exploring the following resources:
if
statement executes a block of code if a condition is true
.else
statement executes a block of code if the if
condition is false
.else if
statement allows you to check multiple conditions.if...else
statements.By mastering conditional statements, you can create more dynamic and interactive web pages. Practice writing conditional logic to solve various problems and enhance your programming skills.