javascript

Conditional Statements

Learn JavaScript conditional statements: if, else if, and else. Make your code smart to perform different actions based on conditions, using switch statements and operators.

10 min read 8 sections Tutorial
Share

Conditional statements are like making decisions in your code. They let your program choose different paths based on whether something is true or false. This makes your programs smart and able to react to different situations.

Conditional Statements

Conditional Statements

Imagine you are playing a game. If your score is high enough, you win. If not, you lose. This "if...then" logic is exactly what conditional statements do in programming.

They allow your JavaScript code to check conditions. Based on whether a condition is true or false, your code will run different parts. This is how programs make choices and respond to user input or data.

What are Conditionals?

Conditional statements are control structures that execute different blocks of code based on whether a specified condition evaluates to true or false.

if

Runs code only if a specific condition is true.

else if

Checks another condition if the first 'if' condition was false.

else

Runs code if all previous 'if' and 'else if' conditions were false.

switch

A different way to handle many choices based on a single value.

Your First 'if' Statement

Getting Started

Your First 'if' Statement

The simplest conditional statement is if. You write if, then a condition inside parentheses (), and then the code to run inside curly braces {}.

The condition inside the parentheses must result in either true or false. If it's true, the code inside the curly braces runs. If it's false, that code is skipped.

javascript
1// Create a variable for the user's age
2let userAge = 12;
3
4// Check if the user's age is greater than or equal to 13
5// The condition `userAge >= 13` will be true or false
6if (userAge >= 13) {
7 // This code runs ONLY if userAge is 13 or more
8 console.log("You are old enough to create an account.");
9}
10
11console.log("Program continues here.");
12
13// Let's try with a different age
14let anotherAge = 18;
15if (anotherAge >= 13) {
16 console.log("This message will show because 18 is >= 13.");
17}

Do not use a single equals sign for comparison

A single equals sign = is for assigning a value to a variable (let x = 10;). A double == or triple === equals sign is for comparing values.

If you accidentally write if (userAge = 13), it will assign 13 to userAge and then treat 13 as true (because it's a non-zero number). This is a common mistake that causes unexpected behavior.

Always use == or === for comparisons in if statements.

Adding 'else' and 'else if'

Adding 'else' and 'else if'

Often, you want to do something if a condition is true, and something else if it's false. That's where the else statement comes in. It provides an alternative path for your code.

If you have many conditions to check, you can use else if. This lets your code check one condition, then another, and then another, until one is true. If none are true, the final else block will run.

javascript
1// Variable for a game score
2let score = 75;
3
4// Check the score to give a rank
5if (score >= 90) {
6 // This runs if score is 90 or more
7 console.log("Rank: Gold Star!");
8} else if (score >= 70) {
9 // This runs if score is NOT >= 90, BUT IS >= 70
10 console.log("Rank: Silver Medal.");
11} else if (score >= 50) {
12 // This runs if score is NOT >= 70, BUT IS >= 50
13 console.log("Rank: Bronze Tier.");
14} else {
15 // This runs if NONE of the above conditions were true
16 console.log("Rank: Try Again.");
17}
18
19// Let's test with a different score
20let finalScore = 40;
21if (finalScore >= 90) {
22 console.log("Gold Star!");
23} else if (finalScore >= 70) {
24 console.log("Silver Medal.");
25} else if (finalScore >= 50) {
26 console.log("Bronze Tier.");
27} else {
28 console.log("Try Again."); // This will print for finalScore = 40
29}
✗ BadWrong — messy nesting
let age = 10;
if (age >= 18) {
console.log("Adult");
} else {
if (age >= 13) {
console.log("Teen");
} else {
console.log("Child");
}
}
✓ GoodCorrect — using else if
let age = 10;
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teen");
} else {
console.log("Child");
}

if/else if vs. switch

if/else if vs. switch

When you have many possible outcomes based on a single value, an if/else if chain can become very long. The switch statement offers a cleaner way to handle these situations.

The switch statement evaluates a single expression. Then it compares the result to several case values. If a match is found, the code for that case runs. If no case matches, the default code runs.

Using if/else if
// Using if/else if for a day of the week
let day = 'Monday';
if (day === 'Monday') {
console.log('Start of the week.');
} else if (day === 'Friday') {
console.log('Almost weekend!');
} else if (day === 'Saturday' || day === 'Sunday') {
console.log('It\'s the weekend!');
} else {
console.log('Midweek.');
}
VS
Using switch
// Using switch for a day of the week
let day = 'Monday';
switch (day) {
case 'Monday':
console.log('Start of the week.');
break;
case 'Friday':
console.log('Almost weekend!');
break;
case 'Saturday':
case 'Sunday':
console.log('It\'s the weekend!');
break;
default:
console.log('Midweek.');
}

When to use switch

Use switch when you are checking a single variable against many possible exact values. For example, if you have a status variable that can be 'pending', 'approved', or 'rejected'.

Use if/else if when you are checking ranges of values (like score >= 90) or complex conditions involving multiple variables (age > 18 && hasLicense).

Building a Simple Price Calculator

Building a Simple Price Calculator

Let's use conditional statements to build a small program that calculates a price with different discounts. This shows how decisions in your code can change the final outcome.

We will apply a discount based on the total purchase amount. More money spent means a bigger discount.

1

Set the initial price

Start with a base price for the items.

javascript
1let basePrice = 250;
2let discount = 0;
3let finalPrice = 0;
2

Apply a discount based on price

Use if, else if, else to decide the discount percentage.

javascript
1if (basePrice >= 500) {
2 discount = 0.20; // 20% off
3} else if (basePrice >= 200) {
4 discount = 0.10; // 10% off
5} else {
6 discount = 0; // No discount
7}
3

Calculate the final price

Apply the chosen discount to the basePrice to get the finalPrice.

javascript
1finalPrice = basePrice * (1 - discount);
2console.log(`Base Price: $${basePrice}`);
3console.log(`Discount Applied: ${discount * 100}%`);
4console.log(`Final Price: $${finalPrice}`);
4

Test with different prices

Change basePrice to see how the discount changes.

javascript
1/* Try changing basePrice to:
2- 100 (no discount)
3- 300 (10% discount)
4- 600 (20% discount)
5*/

Remember 'break' in switch statements

If you forget break; at the end of a case block in a switch statement, JavaScript will continue executing the code in the next case block, even if it doesn't match the value. This is called fall-through and often leads to bugs. Always include break; unless you specifically intend fall-through.

Comparison and Logical Operators

Comparison and Logical Operators

The conditions inside your if statements use comparison operators to check relationships between values. They always return true or false.

Logical operators let you combine multiple conditions. You can check if two things are true at the same time, or if at least one of several things is true.

OperatorMeaningExampleResult
==Equal to (loose)5 == '5'true
===Strictly equal to5 === '5'false
!=Not equal to (loose)5 != '6'true
!==Strictly not equal to5 !== '5'true
>Greater than10 > 5true
<Less than10 < 5false
>=Greater than or equal to10 >= 10true
<=Less than or equal to10 <= 9false
&&AND (both true)true && falsefalse
||OR (at least one true)true || falsetrue
!NOT (reverses true/false)!truefalse

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which statement will execute if score is 85?

Quick Check

What is the primary purpose of the break keyword in a switch statement?

Quick Check

What will console.log(10 == '10'); print?

Quick Check

Which of these JavaScript values is considered 'falsy' in a conditional statement?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1if statement — runs code if a condition is true. Example: if (age > 18) { ... }
  • 2else if — checks another condition if the previous if or else if was false.
  • 3else — runs code if all preceding if and else if conditions were false.
  • 4Conditions — always evaluate to true or false using comparison operators.
  • 5Strict Equality (===) — always prefer === over == to avoid unexpected type conversions.
  • 6Logical AND (&&)condition1 && condition2 is true only if BOTH conditions are true.
  • 7Logical OR (||)condition1 || condition2 is true if at least ONE condition is true.
  • 8switch statement — useful for checking a single variable against many possible exact values.
  • 9break keyword — essential in switch case blocks to prevent 'fall-through' to the next case.
  • 10Ternary Operator — a shortcut for simple if/else assignments: condition ? valueIfTrue : valueIfFalse.

Loops

Learn how to repeat actions in your code using for and while loops.

Functions

Organize your code into reusable blocks to perform specific tasks.

Data Types

Understand different types of values like numbers, strings, and booleans.

Comparison Operators

Dive deeper into how JavaScript compares different values and types.

You've Mastered Conditional Logic!

You now understand how to make your JavaScript programs smart by using if, else if, else, and switch statements. You can use comparison and logical operators to create powerful conditions, allowing your code to react dynamically to different situations and inputs.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning