Learn JavaScript from Scratch, Part 3: Operators and Conditions

Learn JavaScript from Scratch, Part 3: Operators and Conditions - CodingHumans

Programs make decisions: is the password long enough, is the cart empty, is the user logged in? In this part you'll learn JavaScript operators and conditions — including the two things beginners trip on most: == vs === and truthy/falsy values.

This is Part 3 of Learn JavaScript from Scratch, continuing from Part 2.

1. Arithmetic and assignment

5 + 2    // 7        5 % 2   // 1  (remainder)
5 - 2    // 3        2 ** 3  // 8  (power)
5 * 2    // 10       5 / 2   // 2.5

% (remainder) is more useful than it looks: n % 2 === 0 means "n is even", minutes % 60 gives the leftover minutes. Shorthand assignments update a variable in place:

let score = 10;
score += 5;   // score = score + 5  -> 15
score++;      // add 1              -> 16

One trap: + also joins strings. If either side is a string, JavaScript concatenates instead of adding:

"5" + 1    // "51"  - string wins with +
"5" - 1    // 4     - minus only works on numbers, so it converts
Number("5") + 1   // 6 - convert first when input is text

Anything read from an input field is a string, so convert with Number(...) before doing maths on it.

2. Comparisons: == vs ===

Comparisons answer true or false: >, <, >=, <=, and two kinds of equality:

OperatorNameBehaviour
=== / !==Strict equalityEqual only if the type and value match. Use this.
== / !=Loose equalityConverts types first, with surprising rules
5 === "5"    // false - number vs string
5 == "5"     // true  - "5" converted to 5 first
0 == ""      // true  (!)
null == undefined   // true - the one == rule people use on purpose
Rule: always write === and !==. The conversions of == cause bugs that are hard to spot. This is a guaranteed interview question.

3. Truthy and falsy

When JavaScript needs a yes/no answer from a value that isn't a boolean, it converts it. Exactly six values are falsy — everything else is truthy:

false   0   ""   null   undefined   NaN     // the falsy six

So "hello", 42, -1, [] (empty array!) and {} (empty object!) are all truthy. This enables short, idiomatic checks:

if (userName) { ... }   // runs unless userName is "" / null / undefined
if (items.length) { ... }  // runs when the array has items (0 is falsy)

4. Combining conditions: &&, || and !

age >= 18 && hasId     // AND: both must be true
isAdmin || isOwner     // OR: at least one true
!isLoggedIn            // NOT: flips the value

Two behaviours worth knowing early:

  • Short-circuiting: a && b stops at a if it's falsy; a || b stops at a if it's truthy. The right side never even runs.
  • They return the value, not just true/false: const name = input || "Guest" means "input, or Guest if input is falsy". The newer ?? does the same but only treats null/undefined as missing — so 0 ?? 10 is 0, while 0 || 10 is 10.

5. if, else and the ternary

if (marks >= 90) {
  grade = "A";
} else if (marks >= 75) {
  grade = "B";
} else {
  grade = "C";
}

Conditions are checked top to bottom and only the first true branch runs — order matters. For a tiny choose-one-of-two, the ternary operator fits on one line:

const label = count === 1 ? "item" : "items";

Read it as "condition ? value-if-true : value-if-false". Great for one decision; nest them and nobody can read your code.

6. switch - comparing one value to many options

switch (day) {
  case "sat":
  case "sun":
    type = "weekend"; break;
  case "mon":
    type = "week start"; break;
  default:
    type = "weekday";
}

switch compares with ===. The famous trap: without break, execution falls through into the next case. Stacking two cases with no code between them (like sat/sun above) is the one place fall-through is used on purpose.

7. Common mistakes

  • = instead of ===: if (x = 5) assigns 5 to x and is always truthy. Classic typo.
  • Chaining comparisons like maths: 18 < age < 60 doesn't do what you think — write age > 18 && age < 60.
  • Checking equality with NaN: NaN === NaN is false. Use Number.isNaN(x).
  • Forgetting break in switch → silent fall-through bugs.

Practice: test what you learned

Q1. What does 5 === "5" evaluate to, and why?

a) true, the values match

b) true, === converts types first

c) false, the types differ (number vs string)

d) A TypeError

Q2. Which list contains ONLY falsy values?

a) 0, "0", null

b) 0, "", undefined, NaN

c) [], "", 0

d) {}, null, false

Q3. What does "5" + 1 give?

a) "51"

b) 6

c) "6"

d) NaN

Q4. const name = input || "Guest" - when is name "Guest"?

a) Only when input is undefined

b) Only when input is null or undefined

c) Never - || returns true/false

d) Whenever input is falsy, including "" and 0

Q5. In a switch statement, what happens if you forget break after a case?

a) A syntax error

b) Execution falls through and runs the next case too

c) The switch exits immediately

d) The default case runs

Q6. What does the ternary in count === 1 ? "item" : "items" return when count is 3?

a) "item"

b) true

c) "items"

d) 3

FAQ

Is == ever OK to use?

One idiom is widely accepted: x == null is true for both null and undefined, letting you check "is it missing?" in one go. Everywhere else, use ===.

What is the difference between || and ???

|| falls back on any falsy value (0, "", false included). ?? falls back only on null or undefined. For defaults where 0 or "" are valid inputs, ?? is the safe choice.

Why is NaN === NaN false?

NaN means "not a number" - the result of a failed calculation. The floating-point standard defines NaN as unequal to everything, including itself. Check with Number.isNaN(x).

When should I use switch instead of if/else?

When one value is compared against many fixed options (menu choices, status codes), switch reads better. For ranges or combined conditions, if/else is the tool.

Learning with others? Join the CodingHumans WhatsApp community to get each new part of Learn JavaScript as soon as it goes live.

Comments

Answered 0/0Correct 0