0
0
Javascriptprogramming~15 mins

If–else statement in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - If–else statement
What is it?
An if–else statement is a way for a program to make decisions. It checks if a condition is true or false. If the condition is true, it runs one set of instructions. If false, it runs a different set of instructions.
Why it matters
Without if–else statements, programs would do the same thing every time, no matter the situation. This would make software boring and useless because it couldn't react to different inputs or situations. If–else lets programs choose what to do, making them smart and flexible.
Where it fits
Before learning if–else, you should understand basic JavaScript syntax and variables. After mastering if–else, you can learn about switch statements, loops, and functions that use conditions to control flow.
Mental Model
Core Idea
An if–else statement lets your program pick between two paths based on a true or false question.
Think of it like...
It's like deciding what to wear based on the weather: if it's raining, wear a raincoat; else, wear a t-shirt.
┌───────────────┐
│ Check condition│
└──────┬────────┘
       │true
       ▼
  ┌───────────┐
  │ Run 'if'  │
  │ block     │
  └───────────┘
       │
       ▼
     End
       ▲
       │false
┌───────────┐
│ Run 'else'│
│ block     │
└───────────┘
Build-Up - 7 Steps
1
FoundationBasic if statement syntax
🤔
Concept: Learn how to write a simple if statement that runs code only when a condition is true.
In JavaScript, an if statement looks like this: if (condition) { // code runs if condition is true } Example: let age = 18; if (age >= 18) { console.log('You can vote'); } This prints 'You can vote' only if age is 18 or more.
Result
If age is 18 or more, the message 'You can vote' appears in the console.
Understanding the basic if statement is key because it introduces how programs check conditions and decide what to do next.
2
FoundationAdding else for alternative paths
🤔
Concept: Learn how to add an else block to run code when the if condition is false.
The else block runs when the if condition is false: if (condition) { // runs if true } else { // runs if false } Example: let age = 16; if (age >= 18) { console.log('You can vote'); } else { console.log('You are too young to vote'); } Since age is 16, it prints 'You are too young to vote'.
Result
The program prints a message depending on whether age is 18 or more.
Knowing else lets your program handle both yes and no answers, making decisions complete and clear.
3
IntermediateUsing comparison operators in conditions
🤔Before reading on: do you think '==' and '===' do the same thing in JavaScript? Commit to your answer.
Concept: Learn how to write conditions using different comparison operators and understand their differences.
Conditions use operators like: - == (equal value) - === (equal value and type) - != (not equal) - !== (not equal or different type) - >, <, >=, <= (greater or less than) Example: let x = '5'; if (x == 5) { console.log('Equal with =='); } if (x === 5) { console.log('Equal with ==='); } else { console.log('Not equal with ==='); } Output: Equal with == Not equal with ===
Result
The program shows that '==' compares only value, while '===' compares value and type.
Understanding these operators prevents bugs caused by unexpected type conversions in conditions.
4
IntermediateCombining conditions with logical operators
🤔Before reading on: do you think '&&' means both conditions must be true or just one? Commit to your answer.
Concept: Learn how to check multiple conditions together using AND (&&), OR (||), and NOT (!) operators.
You can combine conditions: if (condition1 && condition2) { // runs if both true } if (condition1 || condition2) { // runs if at least one true } Example: let age = 20; let hasID = true; if (age >= 18 && hasID) { console.log('Allowed to enter'); } else { console.log('Not allowed'); } This prints 'Allowed to enter' only if age is 18 or more AND hasID is true.
Result
The program decides access based on two conditions combined logically.
Knowing how to combine conditions lets your program make more complex decisions.
5
IntermediateUsing else if for multiple choices
🤔
Concept: Learn how to check several conditions in order using else if blocks.
When you have many options, use else if: if (condition1) { // runs if condition1 true } else if (condition2) { // runs if condition2 true } else { // runs if none above true } Example: let score = 75; if (score >= 90) { console.log('Grade A'); } else if (score >= 80) { console.log('Grade B'); } else if (score >= 70) { console.log('Grade C'); } else { console.log('Grade F'); } This prints 'Grade C' because score is 75.
Result
The program picks the first true condition and runs its block.
Using else if lets your program handle many cases clearly and efficiently.
6
AdvancedShort-circuit evaluation in conditions
🤔Before reading on: do you think both sides of '&&' always run in JavaScript? Commit to your answer.
Concept: Learn how JavaScript stops checking conditions early when the result is already known (short-circuiting).
In expressions like A && B: - If A is false, B is NOT checked because the whole is false. In A || B: - If A is true, B is NOT checked because the whole is true. Example: function checkA() { console.log('Checking A'); return false; } function checkB() { console.log('Checking B'); return true; } if (checkA() && checkB()) { console.log('Both true'); } else { console.log('At least one false'); } Output: Checking A At least one false Notice 'Checking B' is never printed.
Result
JavaScript skips checking B because A is false, saving time.
Understanding short-circuiting helps write efficient code and avoid errors from unnecessary checks.
7
ExpertTruthiness and falsiness in conditions
🤔Before reading on: do you think all values other than true/false can be used directly in if conditions? Commit to your answer.
Concept: Learn how JavaScript treats different values as true or false automatically in conditions.
JavaScript converts values to boolean in if conditions: Falsy values (treated as false): - false, 0, '', null, undefined, NaN Truthy values (treated as true): - All others, like 'hello', 1, [], {}, function(){} Example: if ('') { console.log('This runs'); } else { console.log('Empty string is falsy'); } Output: Empty string is falsy This means you can write: let name = ''; if (name) { console.log('Name exists'); } else { console.log('Name is empty'); }
Result
The program correctly treats empty strings and other falsy values as false in conditions.
Knowing truthy and falsy values prevents bugs and lets you write cleaner, shorter conditions.
Under the Hood
When JavaScript runs an if–else statement, it first evaluates the condition inside the parentheses. This evaluation converts the condition to a boolean true or false using internal rules (including truthiness and falsiness). Based on this boolean result, the JavaScript engine decides which block of code to execute next. The engine uses a stack to keep track of execution and jumps to the correct code block, skipping the other. Logical operators like && and || use short-circuit evaluation to avoid unnecessary checks, improving performance.
Why designed this way?
If–else statements were designed to mimic human decision-making: checking a condition and choosing a path. Early programming languages adopted this simple control flow to make programs flexible and readable. Short-circuiting was added later to optimize performance and avoid side effects from unnecessary evaluations. JavaScript's truthy/falsy system was designed to allow flexible and concise code, but it requires understanding to avoid confusion.
┌───────────────┐
│ Evaluate cond │
└──────┬────────┘
       │
       ▼
┌───────────────┐     true      ┌───────────────┐
│ Convert to    │──────────────▶│ Execute if    │
│ boolean       │               │ block         │
└──────┬────────┘               └──────┬────────┘
       │false                          │
       ▼                              ▼
┌───────────────┐               ┌───────────────┐
│ Execute else  │◀──────────────│ Skip if block │
│ block        │               └───────────────┘
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 'if (0)' run the if block or skip it? Commit to your answer.
Common Belief:People often think only true and false can be used in if conditions.
Tap to reveal reality
Reality:JavaScript treats many values like 0, '', null, undefined as false (falsy), so 'if (0)' does NOT run the if block.
Why it matters:Misunderstanding this leads to bugs where code runs or skips unexpectedly, especially with empty strings or zero values.
Quick: Does '==' check both value and type strictly? Commit to your answer.
Common Belief:Many believe '==' is the same as '===' and checks both value and type.
Tap to reveal reality
Reality:'==' compares values after converting types, which can cause unexpected true results; '===' checks value and type strictly.
Why it matters:Using '==' can cause bugs when types differ, like '5' == 5 is true but '5' === 5 is false.
Quick: Does the else block run if the if condition is true? Commit to your answer.
Common Belief:Some think else runs after if regardless of the condition.
Tap to reveal reality
Reality:Else runs only if the if condition is false; if true, else is skipped.
Why it matters:Misusing else can cause code to run twice or unexpected behavior.
Quick: Does JavaScript always evaluate both sides of '&&'? Commit to your answer.
Common Belief:People often think both sides of '&&' are always evaluated.
Tap to reveal reality
Reality:JavaScript stops evaluating the second condition if the first is false (short-circuit).
Why it matters:Not knowing this can cause bugs if the second condition has side effects or expensive operations.
Expert Zone
1
JavaScript's truthy/falsy rules include some surprising values like NaN and empty arrays, which can affect condition outcomes subtly.
2
Short-circuit evaluation can be used intentionally to write concise code that avoids errors or unnecessary function calls.
3
The order of else if conditions matters; the first true condition stops further checks, so ordering affects program logic and performance.
When NOT to use
If–else statements become hard to read with many conditions; in such cases, switch statements or lookup tables (objects mapping keys to functions) are better alternatives.
Production Patterns
In real-world code, if–else is often combined with functions to keep code clean. Developers use early returns with if to avoid deep nesting. Also, ternary operators provide a shorthand for simple if–else expressions.
Connections
Boolean algebra
If–else conditions use boolean logic to decide paths.
Understanding boolean algebra helps write correct and optimized conditions in if–else statements.
Decision making in psychology
If–else mimics human decision processes of choosing actions based on conditions.
Knowing how humans make decisions clarifies why if–else is a natural and intuitive programming tool.
Electrical circuits (logic gates)
If–else statements correspond to logic gates that control electrical signals based on inputs.
Recognizing this connection shows how software decisions are rooted in hardware logic, bridging computer science and electronics.
Common Pitfalls
#1Using assignment '=' instead of comparison '==' or '===' in conditions.
Wrong approach:if (x = 5) { console.log('x is 5'); }
Correct approach:if (x === 5) { console.log('x is 5'); }
Root cause:Confusing '=' (assign) with '==' or '===' (compare) causes the condition to always be true because assignment returns the assigned value.
#2Writing if conditions without braces for multiple statements.
Wrong approach:if (x > 0) console.log('Positive'); console.log('Number');
Correct approach:if (x > 0) { console.log('Positive'); console.log('Number'); }
Root cause:Without braces, only the first line is inside the if; the second always runs, causing logic errors.
#3Using else if conditions in wrong order causing unreachable code.
Wrong approach:if (score >= 70) { console.log('Pass'); } else if (score >= 90) { console.log('Excellent'); }
Correct approach:if (score >= 90) { console.log('Excellent'); } else if (score >= 70) { console.log('Pass'); }
Root cause:Placing broader conditions first blocks narrower ones, so some code never runs.
Key Takeaways
If–else statements let programs choose between actions based on conditions, making them flexible and interactive.
Conditions convert values to true or false, using JavaScript's truthy and falsy rules, which must be understood to avoid bugs.
Logical operators and else if blocks allow combining and ordering multiple conditions for complex decisions.
Short-circuit evaluation improves efficiency by skipping unnecessary checks and can prevent errors.
Misusing comparison operators or condition syntax leads to common bugs, so careful attention is essential.