0
0
Javascriptprogramming~15 mins

If statement in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - If statement
What is it?
An if 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 some code. If it is false, it can skip that code or run different code.
Why it matters
Without if statements, programs would do the same thing every time, no matter what. They help programs react to different situations, like a traffic light changing or a user clicking a button. This makes software useful and interactive.
Where it fits
Before learning if statements, you should understand basic programming concepts like variables and expressions. After if statements, you can learn about loops and functions to control program flow even more.
Mental Model
Core Idea
An if statement lets a program choose what to do based on a true or false question.
Think of it like...
It's like deciding whether to carry an umbrella: if it is raining, you take the umbrella; if not, you leave it at home.
┌───────────────┐
│   Condition   │
└──────┬────────┘
       │ true
       ▼
  ┌───────────┐
  │ Run code  │
  └───────────┘
       │
       │ false
       ▼
  ┌───────────┐
  │ Skip code │
  └───────────┘
Build-Up - 7 Steps
1
FoundationBasic if statement syntax
🤔
Concept: Learn the simplest form of an if statement to run code only when a condition is true.
In JavaScript, an if statement looks like this: if (condition) { // code runs only if condition is true } Example: let age = 18; if (age >= 18) { console.log('You can vote'); }
Result
If age is 18 or more, the message 'You can vote' appears in the console.
Understanding the basic if statement is the first step to making programs that react to different situations.
2
FoundationUsing conditions with comparisons
🤔
Concept: Conditions inside if statements often compare values using operators like >, <, ===.
Conditions check if something is true or false. For example: if (score > 50) { console.log('You passed'); } Here, the program checks if score is greater than 50.
Result
If score is more than 50, 'You passed' is printed; otherwise, nothing happens.
Knowing how to write conditions lets you control when code runs based on data.
3
IntermediateAdding else for alternative paths
🤔Before reading on: do you think else runs when the if condition is true or false? Commit to your answer.
Concept: The else part runs code when the if condition is false, giving two paths to choose from.
You can add else to run code when the condition is false: if (temperature > 30) { console.log('It is hot'); } else { console.log('It is not hot'); } This way, the program always prints one message.
Result
If temperature is above 30, it prints 'It is hot'; otherwise, it prints 'It is not hot'.
Using else lets your program handle both yes and no answers clearly.
4
IntermediateUsing else if for multiple choices
🤔Before reading on: do you think else if can check more than one condition? Commit to your answer.
Concept: else if lets you check several conditions in order, running code for the first true one.
Example: if (score >= 90) { console.log('Grade A'); } else if (score >= 80) { console.log('Grade B'); } else { console.log('Grade C or below'); } The program picks the first matching grade.
Result
Depending on score, it prints the correct grade message.
else if helps handle many situations without writing separate if statements.
5
IntermediateBoolean logic in conditions
🤔Before reading on: do you think you can combine conditions with AND and OR? Commit to your answer.
Concept: You can combine conditions using && (AND) and || (OR) to make complex decisions.
Example: if (age >= 18 && hasID) { console.log('Allowed to enter'); } This means both age must be 18 or more AND hasID must be true.
Result
Code runs only if both conditions are true.
Combining conditions lets your program make smarter choices based on multiple facts.
6
AdvancedShort-circuit evaluation in conditions
🤔Before reading on: do you think both sides of && or || always run? Commit to your answer.
Concept: JavaScript stops checking conditions early when the result is already known, saving time.
For && (AND), if the first condition is false, it skips the second. For || (OR), if the first condition is true, it skips the second. Example: if (user && user.isAdmin) { console.log('Admin access'); } If user is null or undefined, user.isAdmin is not checked, avoiding errors.
Result
The program safely checks conditions without crashing.
Knowing short-circuiting helps write safer and faster code.
7
ExpertTruthiness and falsiness in conditions
🤔Before reading on: do you think all values in JavaScript are strictly true or false in if? Commit to your answer.
Concept: JavaScript treats some values as true or false automatically, even if they are not boolean types.
Values like 0, '', null, undefined, and NaN count as false (falsy). Others like non-empty strings, numbers except 0, and objects count as true (truthy). Example: if ('hello') { console.log('This runs'); } if (0) { console.log('This does not run'); }
Result
Code runs or skips based on truthy or falsy values, not just true or false.
Understanding truthiness prevents bugs and helps write concise conditions.
Under the Hood
When JavaScript runs an if statement, it first evaluates the condition inside the parentheses. This evaluation converts the condition to a boolean true or false using internal rules. Then, if the result is true, the code block inside the if runs. If false, it skips to else or else if blocks if present. The engine uses short-circuit logic to avoid unnecessary checks, improving performance and safety.
Why designed this way?
If statements were designed to mimic human decision-making: asking a yes/no question and acting accordingly. Early programming languages adopted this simple control flow to make programs flexible. Short-circuit evaluation was added later to optimize performance and prevent errors when checking multiple conditions.
┌───────────────┐
│ Evaluate cond │
└──────┬────────┘
       │ boolean
       ▼
┌───────────────┐
│ Condition true?│
└──────┬────────┘
   yes │ no
       ▼    ┌───────────────┐
┌───────────┐│ Check else if │
│ Run if code│└──────┬────────┘
└───────────┘       │
                    ▼
               ┌───────────┐
               │ Run else  │
               └───────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does an if statement run its code when the condition is false? Commit yes or no.
Common Belief:If statements run their code block even if the condition is false.
Tap to reveal reality
Reality:If statements only run their code block when the condition is true; otherwise, they skip it.
Why it matters:Believing this causes confusion and bugs because code runs unexpectedly or not at all.
Quick: Does JavaScript treat the number 0 as true or false in an if condition? Commit your answer.
Common Belief:0 is true in if conditions because it is a number.
Tap to reveal reality
Reality:0 is falsy in JavaScript, so conditions like if(0) do not run the code block.
Why it matters:Misunderstanding this leads to unexpected behavior, especially when checking numeric values.
Quick: Does else if run if the previous if condition was true? Commit yes or no.
Common Belief:else if always runs after if, regardless of the first condition.
Tap to reveal reality
Reality:else if only runs if the previous if condition was false.
Why it matters:This misconception causes logic errors where multiple blocks run when only one should.
Quick: Do both sides of && always evaluate in JavaScript? Commit yes or no.
Common Belief:Both sides of && always run to check the full condition.
Tap to reveal reality
Reality:JavaScript stops evaluating && as soon as the first false is found (short-circuit).
Why it matters:Not knowing this can cause bugs or missed side effects in code.
Expert Zone
1
The condition inside if is not always a boolean; JavaScript converts values using truthiness rules, which can surprise even experienced developers.
2
Short-circuit evaluation can be used intentionally to write concise code that avoids errors, like checking if an object exists before accessing its property.
3
Nested if statements can be flattened using logical operators or switch statements for clearer and more maintainable code.
When NOT to use
If statements become hard to read with many conditions; in such cases, use switch statements or lookup tables. For repeated actions, loops are better. For asynchronous decisions, promises or async/await patterns are preferred.
Production Patterns
In real-world code, if statements often validate user input, control feature flags, or handle error cases. They are combined with functions and objects to keep code clean. Developers also use ternary operators for simple if-else expressions to write concise code.
Connections
Boolean logic
If statements use boolean logic to decide which code to run.
Understanding boolean logic deeply helps write more precise and efficient conditions in if statements.
Decision trees (data science)
If statements in code resemble decision trees that split data based on conditions.
Knowing how decision trees work helps understand how complex if-else chains make decisions step-by-step.
Human decision making (psychology)
If statements mimic how humans make choices based on conditions and alternatives.
Recognizing this connection clarifies why if statements are intuitive and fundamental in programming.
Common Pitfalls
#1Forgetting to use curly braces for multiple lines inside if.
Wrong approach:if (score > 50) console.log('Passed'); console.log('Congrats!');
Correct approach:if (score > 50) { console.log('Passed'); console.log('Congrats!'); }
Root cause:JavaScript runs only the first line after if without braces, causing unexpected code to run always.
#2Using assignment = instead of comparison == or === in condition.
Wrong approach:if (age = 18) { console.log('You are 18'); }
Correct approach:if (age === 18) { console.log('You are 18'); }
Root cause:Using = assigns a value instead of comparing, so condition is always true, causing bugs.
#3Confusing == and === leading to unexpected type coercion.
Wrong approach:if (input == 0) { console.log('Zero'); }
Correct approach:if (input === 0) { console.log('Zero'); }
Root cause:== allows type conversion which can cause unexpected true results; === checks both value and type.
Key Takeaways
If statements let programs make choices by running code only when conditions are true.
Conditions use comparisons and boolean logic to decide what path to take.
Else and else if provide alternative paths for when conditions are false.
JavaScript treats many values as true or false automatically, which affects if conditions.
Understanding short-circuit evaluation and truthiness helps write safer and clearer code.