Ad space (banner)
🟨JavaScript Lessons
Lesson 3 / 69

Conditionals (if Statements)

In this lesson you'll learn how to write if statements in JavaScript so you can branch your code based on "if this condition is true." This is an introductory lesson for anyone searching "JavaScript if statement syntax."

An if statement runs its body only when a condition is true. It's written as if (condition) { ... } else { ... }, and the else block runs when the condition is false. Think of it as translating the everyday decision "if it's raining, bring an umbrella" directly into code. Stacking else if lets you express three or more branches.

The sample code prints one of three messages depending on the value of the score variable. Comparisons use operators like >= (greater than or equal), > (greater than), and === (equal to). Conditions are evaluated from top to bottom, and only the block for the first condition that's true gets executed — that's an important detail to internalize.

A very common beginner mistake is confusing = (assignment) with === (comparison) when checking equality. Using = won't throw an error, but it will silently produce unintended behavior, so be careful. Getting the order of conditions wrong is another common cause of bugs, where a branch matches earlier than intended.

In real development, if statements are used everywhere — switching what's displayed based on login state, validating whether input is correct, and so on. Writing accurate conditionals is foundational to writing code with fewer bugs.

if statements can also be nested: "first check the age, and within that, check the membership type" is a way to express multi-stage conditions. But deep nesting quickly becomes hard to read, so once conditions get complex, consider extracting them into a function instead.

Besides === (strict equality), there's also == (loose equality), but == automatically converts types before comparing, which often leads to unintended results — so in practice, === is used almost exclusively.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)