What is an If Else Statement in Programming? (Explained with Example)

Your code runs the same way every time. It does not know if the user is logged in. It does not know if the password is right or wrong. It just runs – blindly, from top to bottom.

That is the problem. Real programs need to make decisions.

If/else statements are how you give your code that ability. One condition. Two possible paths. Your program checks the situation, and chooses what to do next. In this guide, you will learn exactly how it works, with simple examples that make the logic click instantly.

What Is an If/Else Statement? Simple Definition

Simple Definition

An if/else statement tells your program to do one thing if a condition is true — and something else if it is not. One condition. Two possible paths. Your code checks — and chooses.

💬
If/Else Meaning in Plain English

Before this — your code ran the same way every single time. It could not check anything. It could not decide anything. If/else changes that completely. You give the program a question. It checks the answer. If the answer is yes — it does one thing. If no — it does another. That is decision-making in code. I remember when this clicked — suddenly I could build things that actually responded to the user.

🚦
Real-Life Analogy — Traffic Lights

Think of a traffic light. If the light is green — you go. If it is not green — you stop. No maybe. No grey area. Just true or false — and a clear action for each. That is exactly how if/else works in code.

🚦 Traffic light — if/else in real life Analogy
✓ If light === “green”
console.log(“Go!”);
// ✓ runs this path
✗ Else — any other colour
console.log(“Stop!”);
// ✗ skipped if green

📋
How If/Else Works Step by Step

Every if/else in every language follows the same five steps. Learn this order once and it works in JavaScript, Python, Java — everywhere.

📋 What happens inside every if/else
1
Program reaches the if statement
Execution stops here and prepares to check something
2
Checks the condition inside ( )
Evaluates the expression — result is always true or false
3
Condition is true → runs the if block
Everything inside { } executes — else block is skipped
4
Condition is false → runs the else block
if block is skipped completely — else block runs instead
5
Program continues normally after both blocks
Code after the if/else always runs — regardless of which path was taken
🎯
One condition. Two paths. Only one runs. Never both. Never neither. That rule never changes — no matter how complex your conditions get later.

The Basic If Statement

The simplest form of decision-making in code. Runs a block only when a condition is true. No else needed — just a single check.

JavaScript
Python
⚡

Syntax in JavaScript

( ) for condition { } for block

JavaScript uses parentheses ( ) around the condition and curly braces { } around the code block. Forget either one — you get a SyntaxError. I forgot the curly braces more times than I want to admit when I was starting out.

if (condition) {
  // code runs only when condition is true
}
check.js
let age = 20;

if (age >= 18) {
  console.log(“Access granted”); // ✓ runs
}
🐍

Syntax in Python

: colon indentation

Python is cleaner — no parentheses, no curly braces. You just write the condition, add a colon : at the end, and indent the block below it. Indentation is not optional in Python — it is how the language knows what belongs inside the if block.

if condition:
  # indented code runs when true
check.py
age = 20

if age >= 18:
  print(“Access granted”) # ✓ runs
⚡ JavaScript uses

( ) around condition
{ } for the block

🐍 Python uses

No ( ) needed
: + indentation

❌

What Happens When the Condition is False?

No else yet

With just an if and no else — nothing happens when the condition is false. The program simply skips the block and moves to the next line. No error. No output. Just silence — and the code continues.

let age = 15; ✓ Runs
if (age >= 18) { Checked
  console.log(“Access granted”); ✗ Skipped
} ✓ Runs
console.log(“Program continues”); ✓ Always runs
🎯
Code after the if block always runs — no matter what. Only the code inside the curly braces gets skipped when the condition is false. Everything else continues normally.

If/Else — Two Paths

A basic if only runs when true. But what about false? The else block catches that. Together they give your program exactly two paths — one for true, one for false.

🔀
Adding the Else Block

The else block runs when the if condition is false. You never need to write another condition for it — it just catches everything the if did not. One of the two will always run. Never both. Never neither. That guarantee is what makes if/else so reliable.

🔀 if condition → two possible paths Visual
if (condition) ?
▼
✅ TRUE
if block runs ✓
|
❌ FALSE
else block runs ✓
if (condition) {
  // runs when TRUE
} else {
  // runs when FALSE
}

🔐
Real Code Example — Login Check

A login check is the perfect real-world example of if/else. Either the password is correct — or it is not. No third option exists. This is one of the first things I built when I was learning — and it made if/else feel completely real.

🎯
One of the two blocks always runs — guaranteed. If/else is the foundation of every decision your program will ever make. Master this and everything that follows becomes much easier.

Else If — Checking Multiple Conditions

What if you need more than two paths? else if lets you chain as many conditions as you need — each one checked in order, top to bottom.

⚡

else if in JavaScript

else if

Write else if — two separate words — after the if block. Each one adds another condition to check. Only the first true condition runs — the rest are skipped.

if (x === 1) {
  // first check
} else if (x === 2) {
  // second check
} else {
  // none matched
}
🐍

elif in Python

elif

Python shortens it to elif — one word. Same logic — checks the next condition only if the previous ones were false. Cleaner to type, same result.

if x == 1:
  # first check
elif x == 2:
  # second check
else:
  # none matched

🎓
Real-Life Grade Checker Example

A grade checker is the classic else if example — multiple score ranges, one result each. The first matching condition wins — all others are ignored.

🎓
Grade Checker — else if chain
JavaScript
if score >= 90 A
else if score >= 75 B
else if score >= 60 C
else anything below 60 F
let score = 82;

if (score >= 90) {
  console.log(“Grade: A”);
} else if (score >= 75) {
  console.log(“Grade: B”); // ✓ this runs
} else if (score >= 60) {
  console.log(“Grade: C”);
} else {
  console.log(“Grade: F”);
}
Output → Grade: B
🎯
Order matters in else if chains. The first condition that is true wins — and the rest are never checked. Always put your most specific conditions first.

Nested If/Else — Conditions Inside Conditions

Sometimes one check is not enough. Nested if/else lets you check a second condition only after the first one passes.

When to Use Nested If H3

Use nested if when the second check only makes sense if the first check passed. Not every decision fits into a single if/else — some require a two-step gate. Think of it as checking ID at the door, then checking the ticket at the entrance.

01 User is logged in — then check if they have a subscription
02 Age is above 18 — then check if they have a valid ID
03 File exists — then check if the user has permission to open it

Simple Nested Example H3

Here the program first checks if the user is logged in. Only if that passes — it then checks if they have admin access. The inner if only runs when the outer if is true.

🎁 Nested if — two-level check
Nested
if (isLoggedIn === true) {
Outer if
  // user is logged in — now check role
  if (role === “admin”) {
Inner if
    console.log(“Admin dashboard”); // ✓
  } else {
Inner else
    console.log(“User dashboard”);
}
If admin → “Admin dashboard”
⚠️
Do not go too deep. More than two levels of nesting makes code very hard to read. If you find yourself nesting three levels deep — it is usually a sign to rethink the structure.
🎯
Nested if = a gate inside a gate. Only use it when the inner condition genuinely depends on the outer one passing first.

Combining Conditions With Logical Operators

Sometimes one condition is not enough. Logical operators let you combine two or more conditions inside a single if statement — without nesting.

&& AND

Using && (AND) in an If Statement

Both conditions must be true. If even one is false — the whole if block is skipped. Use && when all requirements must pass. I use this for login checks — user must be logged in AND verified.

if (isLoggedIn && isVerified) {
  console.log(“Welcome!”); // both must be true
}
true && true→true
true && false→false
false && false→false
|| OR

Using || (OR) in an If Statement

Only one condition needs to be true. The if block runs if any one passes. Use || when any option is acceptable. Perfect for discounts — student OR senior both qualify.

if (isStudent || isSenior) {
  console.log(“Discount applied!”);
}
true || false→true
false || true→true
false || false→false
! NOT

Using ! (NOT) in an If Statement

Flips the result. True becomes false. False becomes true. Use ! when you want the opposite. Show the login button only when the user is NOT already logged in.

if (!isLoggedIn) {
  console.log(“Please log in”);
}
!true→false
!false→true
🎯
&& is strict. || is flexible. ! flips. Combine them inside any if statement — and you can handle almost any real-world decision your program needs to make.

The Ternary Operator — One-Line If/Else

The ternary operator is a shortcut for simple if/else statements. Same logic — written in a single line. Once you see it, you will recognize it everywhere.

Ternary Syntax Explained H3

Three parts separated by ? and : — that is where the name “ternary” comes from. Condition ? if true : if false. The first time I saw this, I thought it was a typo. It is not — it is one of the most useful shortcuts in JavaScript.

⚡ Ternary — colour-coded breakdown Syntax
condition ? value if true : value if false
condition to check
? = “if true”
runs when true
: = “else”
runs when false
✗ if/else — 5 lines
let msg;
if (age >= 18) {
  msg = “Adult”;
} else {
  msg = “Minor”;
}
✓ Ternary — 1 line
let msg =
  age >= 18
  ? “Adult”
  : “Minor”;
// same result ✓

When to Use — and When NOT To H3

Ternary is great for simple, short decisions. But when the logic gets complex — stick to if/else. A ternary that spans three lines and has nested conditions is harder to read than the if/else it replaced.

✓ Use Ternary When
Simple true/false result
Assigning one of two values
Short, readable in one line
No side effects needed
✗ Avoid Ternary When
Logic is complex or long
You need multiple actions
Nesting two ternaries
Readability suffers
⚡
Ternary = shortcut, not a replacement. Use it when it makes your code cleaner. The moment it makes things harder to read — switch back to if/else.

Truthy and Falsy Values in JavaScript

JavaScript does not just check true or false. It treats certain values as “falsy” — behaving like false inside an if statement — even when they are not literally the word false.

❓
What Are Falsy Values?

JavaScript has six falsy values — values that behave like false inside an if statement, even when they look like real data. Everything else is truthy — including empty arrays, empty objects, and the string “false.” This surprised me when I first learned it.

❌
Falsy Values 6 total
false boolean false falsy
0 zero falsy
“” empty string falsy
null null falsy
undefined not set falsy
NaN not a number falsy
✅
Truthy Examples everything else
true boolean true truthy
1 any number truthy
“hello” any string truthy
[] empty array truthy
{} empty object truthy
“false” string “false” truthy

⚡
Why This Matters in If Statements

Because JavaScript checks truthiness — you can pass a variable directly into an if statement without comparing it to anything. If the value is truthy — the block runs. If it is falsy — it does not. Clean and fast.

⚡ Truthy/Falsy in if statements
Live Example

You do not need === true every time. JavaScript checks the value’s truthiness automatically. Empty string “” → falsy → block skipped. Any text → truthy → block runs.

let name = “”; Falsy
if (name) { console.log(“Hi!”); } ✗ Skipped
name = “Sara”; Truthy
if (name) { console.log(“Hi!”); } ✓ Runs
🎯
Memorize the 6 falsy values. Everything else is truthy. That rule alone will prevent a surprising number of beginner bugs inside if statements.

Common Mistakes Beginners Make With If/Else

I made all three of these. Each one produces a bug that is surprisingly hard to find — because the code runs without throwing an error.

Mistake 01

Forgetting Curly Braces

🔧

Without curly braces — only the very next line belongs to the if block. Everything after it runs regardless of the condition. This looks fine but behaves completely wrong — and no error appears to tell you.

Fix → Always use curly braces — even for single-line if blocks.
✗ No braces
if (age >= 18)
  console.log(“Adult”);
// only this line is in if
✓ With braces
if (age >= 18) {
  console.log(“Adult”);
} // clear boundary ✓
Mistake 02

Using = Instead of === in Conditions

⚠️

Writing = inside an if condition does not compare — it assigns. The condition then always evaluates as true because the assigned value becomes the result. This is one of the most common silent bugs in JavaScript.

Fix → Inside if( ) — always use === to compare, never =.
✗ Assigns
if (score = 10) {
  // always runs!
}
✓ Compares
if (score === 10) {
  // only when true ✓
}
Mistake 03

Wrong Order in Else If Chains

🔀

The first matching condition wins — always. If you put a broad condition before a specific one, the specific one never runs. Always put your most specific conditions first — most general at the bottom.

Fix → Most specific first, most general last. Order is everything.
✗ Wrong order
if (score >= 60) { // catches 90+ too!
} else if (score >= 90) {
  // never reached!
}
✓ Correct order
if (score >= 90) { // specific first
} else if (score >= 60) {
  // works correctly ✓
}
💡
All three bugs run silently. No red error. No crash. Just wrong behavior. That is what makes them so tricky — and why knowing them upfront saves real time.

Frequently Asked Questions About If/Else

Short, clear answers — no fluff.

Q
Q 01

What is an if else statement with an example?

💡

An if/else statement runs one block when a condition is true — and a different block when it is false. One condition. Two possible outcomes. Only one runs.

if (age >= 18) {
  console.log(“Adult”); // ✓ runs if true
} else {
  console.log(“Minor”); // runs if false
}
Q
Q 02

What is the difference between if and else if?

🔀

if checks the first condition. else if adds another — only checked when the previous one fails.

if Always checked first — runs if true
else if Only checked when if was false
Q
Q 03

Can you have multiple else if statements?

📋

Yes — as many as you need. Only the first matching condition runs — all the rest are skipped instantly.

if (x) {} // 1st check
else if (y) {} // 2nd
else if (z) {} // 3rd
else {} // fallback ✓
✓ Yes — chain as many as needed
🚀
Ready for the next concept? Up next — Loops. Learn how to repeat code automatically instead of writing it over and over.