How to Use Conditional Statements in JavaScript (With Examples)
What is the if statement used for
The if statement in JavaScript is used to make decisions in a program. It allows the program to execute a block of code only when a specific condition is true. It has the following syntax:
if (condition){
// Code to execute if the condition is true
}
Example:
var age = 18;if (age >= 18){console.log("You are eligible to vote.");}
Output:
You are eligible to vote.
In this example, the message is printed only if the value of age is 18 or more.
How to use the if/else statements in JavaScript
if/else statements are how programs process yes/no questions programmatically. If the first condition evaluates to true, then the program will run the first block of code. Otherwise, it will run the else block. Here is the syntax of the if/else statements:
if (condition){
// code to execute if condition is true
}
else{
// code to execute if condition is false
}
Example:
let weather = "rainy";if(weather === "rainy") {console.log("Don't forget an umbrella today!");}else {console.log("It might be nice out today"!);}
Output:
Don't forget an umbrella today!
Using else if for multiple conditions
else if statements are used to add more conditions to an if/else statement. It has the following syntax:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else if (condition3) {
// code if condition3 is true
} else {
// code if none of the above conditions are true
}
Example:
let weather = "sunny";if(weather === "rainy") {console.log("Don't forget an umbrella!");} else if (weather === "sunny"){console.log("Let's grab some sunscreen!");} else {console.log("It might be nice out today"!);}
Output:
Let's grab some sunscreen!
What are truthy and falsy values
In JavaScript, all values are either “truthy” or “falsy.” This means they evaluate to true or false when used in conditional statements. Most values are truthy by default, except for the following falsy values:
false0and-0""and''(empty strings)nullundefinedNaN(not a number)
Note: You can use the logical NOT operator (
!) to convert a truthy value into a falsy one, and vice versa.
Example:
console.log(!undefined);
Output:
true
Understanding comparison operators
Comparison operators in JavaScript are used to compare two values. These include:
<(less than)>(greater than)<=(less than or equal to)>=(greater than or equal to)===(strict equality)!==(strict inequality)
The comparisons evaluate to a boolean value, either true or false.
Example:
console.log(8 !== 8);console.log(5 <= 9);console.log(true === "true");
Output:
falsetruefalse
Using logical operators
Logical operators help us combine multiple conditions. They allow us to determine if both or either of the compared values are truthy or falsy.
Use && to check if both values are true. Use || to check if either of the values is true. Here is a table to understand the behavior of && and ||:
| firstValue | secondValue | firstValue && secondValue | firstValue || secondValue |
|---|---|---|---|
| true | true | true | true |
| true | false | false | true |
| false | true | false | true |
| false | false | false | false |
Example:
let num = 16;if(num > 15 && num < 17) {console.log("Your number is a perfect square!");}
Output:
Your number is a perfect square!
What is a switch statement
A collection of case statements that are compared to the switch condition and evaluated when the condition and case are true. A break is used between the cases to prevent additional execution. A default case gets evaluated when none of the cases are true. A switch statement accomplishes the same task an if/else if/else does in shorter lines of code.
let color = "green";switch(color) {case "orange":console.log("A mix of red and yellow");break;case "green":console.log("A mix of blue and yellow");break;default:console.log("Not sure about this one!");break;}
Output:
A mix of blue and yellow
How to use ternary operator
A ternary operator is a shorthand syntax for an if/else statement. The syntax of ternary operator is:
condition ? value_if_true : value_if_false;
condition: The expression that is evaluated. It can be any expression that returnstrueorfalse.- If
conditionistrue,value_if_trueis returned. - If
conditionisfalse,value_if_falseis returned.
Example:
let temperature = 190;temperature >= 212 ? console.log("It has boiled!") : console.log("It hasn't reached boiling temperature yet.");
Output:
It hasn't reached boiling temperature yet.
Conclusion
Conditional statements are essential for controlling program flow in JavaScript, allowing developers to make decisions based on specific conditions. Understanding how to use if/else, else if, switch, logical operators, and the ternary operator will enable you to write more dynamic and flexible code.
Want to dive deeper into JavaScript? Check out the Learn JavaScript course on Codecademy, where you can practice using these concepts in real coding exercises.
Frequently asked questions
1. What is the difference between if/else and else if in JavaScript?
An if/else statement is used to run code when a condition is true or false. An else if statement allows for multiple conditions to be evaluated in sequence. It is used when you need to check several conditions one after the other.
2. When should I use a switch statement instead of if/else?
A switch statement is more efficient when you need to evaluate a single variable against multiple values. It simplifies code and makes it more readable, especially when handling multiple conditions.
3. What are truthy and falsy values in JavaScript?
Truthy values are values that evaluate to true in a boolean context, such as non-zero numbers or non-empty strings. Falsy values are those that evaluate to false, including 0, null, undefined, and empty strings.
4. How does the ternary operator work in JavaScript?
The ternary operator is shorthand for the if/else statement. It evaluates a condition, and if true, it executes the first expression; if false, it executes the second expression.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
JavaScript Conditional Statements Explained with Examples
Learn about JavaScript conditional statements, including `if`, `if...else`, `if...else if...else`, `switch`, and ternary operators. Understand syntax, examples, and best practices. - Article
JavaScript Switch Case vs If-Else Statement: When to Use Each
Learn when to use the JavaScript `switch` case and `if-else` statement for better code readability and efficiency. Make the right choice for your next project! - Article
Guide to Using Ternary Operator in Python
Learn how the ternary operator works in Python compared to if-else statements, its advantages and disadvantages, and some best practices for using it.
Learn more on Codecademy
- Learn how to control the flow of execution using conditional statements.
- Beginner Friendly.1 hour
- Write programs that handle complex decision-making using the boolean data type, conditionals, and comparison and logical operators.
- Beginner Friendly.3 hours
- Learn how to control the flow of a program and use JavaScript to power dynamic behaviors on websites.
- Beginner Friendly.4 hours
- What is the `if` statement used for
- How to use the if/else statements in JavaScript
- Using else if for multiple conditions
- What are truthy and falsy values
- Understanding comparison operators
- Using logical operators
- What is a switch statement
- How to use ternary operator
- Conclusion
- Frequently asked questions