Please enable JavaScript to use CodeHS

JavaScript Tutorial

If/Else Statements in JavaScript

Programs run top to bottom until you teach them to make decisions. Learn how if, else, and else if let your JavaScript pick a path, just like a traffic light picks a signal.

javascript ~20 min Beginner friendly
The Big Idea

What are if statements?

Computers read programs sequentially: one command at a time, from top to bottom. But most of the time we want our programs to react to the user or to the outside world instead of doing the exact same thing every run. To do that, we use control structures, and one of the most important ones is the if statement. An if statement runs a chunk of code only if a certain condition is true.

You already use if statements in everyday life:

  • If it's raining, I'll grab an umbrella.
  • If I enter the correct passcode, my phone unlocks.

Notice what's implied: if it's not raining, no umbrella. If the passcode is wrong, the phone stays locked. An if statement lets you tell the computer the same thing: only run this code when a specific condition is true.

The conditions inside if statements are boolean expressions, which are perfect for the job because they are always either true or false. If the expression is true, the code inside the curly braces runs. If it's false, the computer skips that code entirely and keeps moving through the program.

Here it is in action. This program checks a boolean variable before letting Karel in. Press Run:

default.js
let correctPassword = true;

if (correctPassword) {
    println("Welcome Karel!");
}
Console
Welcome Karel!

Explore: what type of variable is correctPassword? And what would happen if you changed its value to false and ran the program again? (Answer: it's a boolean, and with false the program prints nothing at all. The if block is skipped and the program simply ends.)

Syntax

Anatomy of a JavaScript if statement

Every if statement in JavaScript has the same two-part costume: parentheses around the condition, and curly braces around the code to run.

if (boolean expression)( ) holds the condition {
    // code to be executed only
    // if the expression is true
}{ } wraps the code to run

Coming from Python? Python marks the condition with a colon and the body with indentation. JavaScript doesn't care about indentation at all: the parentheses ( ) mark the condition and the curly braces { } mark the body. We still indent in JavaScript, but only to make the code easy for humans to read.


Building Conditions

Comparison operators

Most conditions compare two values. JavaScript gives you a toolbox of comparison operators that each produce a boolean answer:

OperatorMeaningExampleResult
===equal to (strict)7 === 7true
!=not equal to3 != 5true
<less than4 < 4false
>greater than9 > 2true
<=less than or equal to4 <= 4true
>=greater than or equal to1 >= 2false

One equals sign is not a comparison! A single = assigns a value to a variable. To compare for equality, use ===. Writing if (score = 100) would overwrite your score instead of checking it.

Interactive

The === vs == lab

JavaScript actually has two equality operators, and they don't always agree. == (loose equality) tries to be helpful: if the two values have different types, it converts one of them and then compares. === (strict equality) is stricter: the values must have the same type and the same value, no conversions allowed.

Pick two values below and see how the operators disagree:

Equality lab
Loose equality
5 == "5"
true
Strict equality
5 === "5"
false

Why programmers prefer ===: the number 5 and the text "5" look alike, but they are different kinds of things, like a five-dollar bill and a photo of one. == squints and says "close enough," which can hide bugs. === tells you the truth, so it's the safer habit. Use === unless you have a very good reason not to.


Two Paths

Adding else

What if you want your program to do something when the boolean expression is false too? Use an if/else statement. The else block is the backup plan: it runs exactly when the condition doesn't.

structure.js
if (boolean expression) {
    // code to be executed only
    // if the expression is true
} else {
    // code to be executed if the
    // boolean expression is false
}

Here's the password program again, upgraded with an else branch. Run it:

default.js
let correctPassword = true;

if (correctPassword) {
    println("Welcome Karel!");
} else {
    println("Incorrect password.");
}
Console
Welcome Karel!

Explore: now change correctPassword to false. This time the program doesn't stay silent like the first example. It prints Incorrect password. instead, because an if/else always runs exactly one of its two blocks.

Many Paths

Chaining with else if

Two paths are great, but sometimes you need more. By adding else if between your if and your else, you can check as many conditions as you like. JavaScript tries them from top to bottom and runs the first one that's true. If none are true, the final else catches everything left over.

This program figures out a shape from the number of sides the user types in. Run it (the user enters 4):

default.js
let numSides = readInt("How many sides? 3, 4, 5: ");

if (numSides === 3) {
    println("Your shape is a triangle. The sturdiest of all shapes.");
} else if (numSides === 4) {
    println("Your shape is a quadrilateral, the most versatile of all shapes.");
} else {
    println("Your shape is a pentagon, the shape that is most likely to follow the rules.");
}
Console
How many sides? 3, 4, 5: 4
Your shape is a quadrilateral, the most versatile of all shapes.

Explore: what happens when the user enters 5? There's no condition checking for 5, so the final else scoops it up and declares a pentagon. In fact, entering 100 would print the pentagon message too! If you changed the last branch to else if (numSides === 5), only an exact 5 would match, and every other number would print nothing.

Why not three separate if statements? Three stand-alone ifs would all be checked, every single run. An if/else-if/else chain stops at the first true condition and skips the rest, which is faster and says what you mean: these choices are alternatives, and exactly one should happen.


Interactive

Branch inspector: the game over screen

Time to watch a real else-if chain think. This game-over screen awards a medal based on your score. Drag the slider and watch each condition evaluate to true or false: the winning branch lights up green, the skipped branches dim, and the console shows what actually prints.

score
72
let score = 72;if (score >= 100) {    println("Gold medal! Incredible run.");} else if (score >= 50) {    println("Silver medal! So close to gold.");} else {    println("Game over. Try again!");}
?
Console

Watch closely at exactly 100: the first condition score >= 100 becomes true, so the chain stops right there. The silver check is never even asked, even though 100 >= 50 would also be true. First true branch wins, everything after is skipped.


Your Turn

Practice: can you drive?

1

Can You Drive?

Write a program that prompts the user for their age and determines if they are eligible to drive (16+ years old). When run, your program should look something like this:

Expected output (age 17)
What is your age?: 17
You can drive!
Expected output (age 13)
What is your age?: 13
Sorry, you are too young to drive.

Hint: look back at the shapes example to see how to get a number from the user with readInt. Then think about which comparison operator says "16 or older."

solution.js
let age = readInt("What is your age?: ");

if (age >= 16) {
    println("You can drive!");
} else {
    println("Sorry, you are too young to drive.");
}
Console (if the user types 17)
What is your age?: 17
You can drive!

The key is age >= 16: "greater than or equal to" includes 16 itself. If you wrote age > 16, a brand-new 16-year-old driver would be told they're too young!


Code

A JavaScript grade checker

JavaScript conditionals use if, else if, and else. This program gives a grade based on a score.


Check Yourself

Quick quiz

1. In a JavaScript if statement, what goes inside the parentheses ( )?

2. What does 5 === "5" evaluate to in JavaScript?

3. What does this program print?

let temp = 75;

if (temp >= 90) {
    println("Stay inside!");
} else if (temp >= 70) {
    println("Perfect day!");
} else {
    println("Bring a jacket.");
}

Keep learning JavaScript

If/else statements let your program choose a path. Next, level up your conditions with booleans and logical operators, or make your decisions repeat with for loops.