Bird
Raised Fist0
Javascriptprogramming~15 mins

If statement in Javascript - Deep Dive

Choose your learning style10 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.

Practice

(1/5)
1. What does an if statement do in JavaScript?
easy
A. Declares a variable
B. Repeats code multiple times
C. Defines a new function
D. Runs code only if a condition is true

Solution

  1. Step 1: Understand the purpose of an if statement

    An if statement checks a condition and runs code only when that condition is true.
  2. Step 2: Compare options with the definition

    Only Runs code only if a condition is true matches this behavior exactly.
  3. Final Answer:

    Runs code only if a condition is true -> Option D
  4. Quick Check:

    If statement = runs code if true [OK]
Hint: If it runs code only when true, it's an if statement [OK]
Common Mistakes:
  • Confusing if with loops
  • Thinking if declares variables
  • Mixing if with function definitions
2. Which of the following is the correct syntax for an if statement in JavaScript?
easy
A. if condition { console.log('Yes'); }
B. if (condition) console.log('Yes');
C. if condition: console.log('Yes');
D. if (condition) then { console.log('Yes'); }

Solution

  1. Step 1: Recall JavaScript if syntax

    The condition must be inside parentheses, and the code block can be inside curly braces or a single statement without braces.
  2. Step 2: Check each option

    if (condition) console.log('Yes'); correctly uses parentheses around the condition and a statement without braces.
  3. Final Answer:

    if (condition) console.log('Yes'); -> Option B
  4. Quick Check:

    Parentheses around condition = correct syntax [OK]
Hint: Condition must be in parentheses for if [OK]
Common Mistakes:
  • Omitting parentheses around condition
  • Using colons instead of braces
  • Adding 'then' keyword (not in JS)
3. What will be the output of this code?
let x = 10;
if (x > 5) {
  console.log('Big');
} else {
  console.log('Small');
}
medium
A. Small
B. 10
C. Big
D. No output

Solution

  1. Step 1: Evaluate the condition x > 5

    Since x is 10, which is greater than 5, the condition is true.
  2. Step 2: Determine which block runs

    The if block runs and prints 'Big'. The else block is skipped.
  3. Final Answer:

    Big -> Option C
  4. Quick Check:

    10 > 5 is true, so output is 'Big' [OK]
Hint: Check if condition is true to pick output [OK]
Common Mistakes:
  • Choosing else output when condition is true
  • Confusing variable value with output
  • Ignoring else block
4. Find the error in this code:
if x == 5 {
  console.log('Equal');
}
medium
A. Missing parentheses around condition
B. Using double equals instead of triple equals
C. Missing semicolon after console.log
D. Curly braces should be parentheses

Solution

  1. Step 1: Check if statement syntax

    In JavaScript, the condition must be inside parentheses after if.
  2. Step 2: Identify the error

    The code misses parentheses around x == 5, causing a syntax error.
  3. Final Answer:

    Missing parentheses around condition -> Option A
  4. Quick Check:

    Condition needs parentheses in if [OK]
Hint: Always put condition inside parentheses in if [OK]
Common Mistakes:
  • Omitting parentheses around condition
  • Confusing == and === (both valid but different)
  • Thinking semicolon is mandatory after console.log
5. You want to print 'Adult' if age is 18 or more, otherwise 'Minor'. Which code correctly uses an if statement?
hard
A. if (age >= 18) { console.log('Adult'); } else { console.log('Minor'); }
B. if age >= 18 then { console.log('Adult'); } else { console.log('Minor'); }
C. if (age > 18) { console.log('Adult'); } else { console.log('Minor'); }
D. if (age = 18) { console.log('Adult'); } else { console.log('Minor'); }

Solution

  1. Step 1: Check condition for age 18 or more

    The condition should be age >= 18 to include 18 and above.
  2. Step 2: Verify syntax and logic

    if (age >= 18) { console.log('Adult'); } else { console.log('Minor'); } uses correct syntax and condition. if age >= 18 then { console.log('Adult'); } else { console.log('Minor'); } uses invalid 'then'. if (age > 18) { console.log('Adult'); } else { console.log('Minor'); } excludes age 18. if (age = 18) { console.log('Adult'); } else { console.log('Minor'); } uses assignment (=) instead of comparison (== or >=).
  3. Final Answer:

    if (age >= 18) { console.log('Adult'); } else { console.log('Minor'); } -> Option A
  4. Quick Check:

    Use >= and correct syntax for if-else [OK]
Hint: Use >= for 18 or more, no 'then' keyword [OK]
Common Mistakes:
  • Using assignment (=) instead of comparison
  • Using 'then' keyword (not in JS)
  • Using > instead of >= to include 18
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard