Beginner level · Module 2: Logic and Functions in JavaScript · Lesson 1 of 3
Conditions and Comparisons
Make decisions with if/else and switch, compare values with strict equality and understand truthy and falsy values.
In this lesson you will
- Use === and !== instead of == and !=
- Write if/else chains and recognise truthy and falsy values
Key concepts
strict equality ===&&, || and !truthy and falsyswitch
The lesson
Always compare with === and !==, which check value and type: 5 === "5" is false. The loose == converts types first, so 0 == "" is true — a frequent source of bugs.
In conditions, JavaScript treats some values as false: false, 0, "" (empty string), null, undefined and NaN. Everything else is truthy. if (name) is a short way to check that a name is not empty, but be careful when 0 is a valid value.
if / else if / else runs the first branch whose condition is true. switch suits comparing one value against many fixed options; remember break in each case.
Step by step
- Compare 5 and "5" with == and === in the console.
- List the six falsy values and test them in if statements.
- Write an if / else if chain that grades a mark.
- Rewrite a day-of-week choice as a switch.
Practice activity
Write a fee status checker that prints 'Paid', 'Part paid' or 'Not paid' for a fee and an amount paid, and rejects negative amounts.
Expected result: Each combination of fee and payment produces the right status, and negative amounts are rejected.
Check your understanding
-
What is the difference between == and ===?
Show answer
=== compares without type conversion; == converts types first.
-
Is 0 truthy or falsy?
Show answer
Falsy.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.