Conditions (if/else)
๐ What are conditions in JavaScript? They let your script **branch**: run one path when something is true, another when it is false. Use `if`, `else if`, and `else` with conditions in parentheses.

Appy Saysโฆ
JavaScript has all the same conditionals as Python, but there's one powerful addition: the ternary operator. It lets you write a simple if/else in a single line โ used constantly in modern React apps.
Conditions in JavaScript
JavaScript uses if / else if / else โ the same logic as Python but with curly braces {} instead of indentation.
- โข
if (condition) { ... }โ runs when condition is truthy - โข
else if (condition) { ... }โ chains additional checks - โข
else { ... }โ the fallback - โขStrict equality: use
===(not==) to compare both value AND type - โขTernary:
const label = score >= 50 ? "Pass" : "Fail";
=== vs == โ strict bouncer vs lazy bouncer
The double equals == is a lazy bouncer โ it accepts "5" == 5 as true because it converts types. The triple equals === is strict โ it checks type AND value, so "5" === 5 is false. Always use strict equality to avoid sneaky bugs.
Real-World Examples
- โขButton text:
const btnText = isLoading ? "Loading..." : "Submit"; - โขTheme toggle:
const theme = isDark ? "dark" : "light"; - โขAuth guard:
if (!isLoggedIn) { redirect('/login'); } - โขGrade display:
if (score >= 90) grade = 'A*'; else if (score >= 80) grade = 'A'; ...
Key Facts
- โขTruthy/falsy:
0,"",null,undefined,NaNare all falsy in JS โ treated as False in conditions - โขThe
!operator negates:if (!isLoggedIn)means 'if not logged in' - โข
switch (value) { case x: ... }โ useful for many possible values - โขLogical AND:
&&; logical OR:||; nullish coalescing:??
Remember
Always use === instead of == in JavaScript. The triple equals checks both value and type, preventing a whole class of subtle bugs that beginners (and even pros) fall into with ==.
What You Learned
- โข
if () {} else if () {} else {}with curly braces (not indentation) - โขAlways use
===for comparison (strict, checks type too) - โขTernary:
condition ? valueIfTrue : valueIfFalse - โขFalsy values:
0,"",null,undefined,NaN - โขLogical operators:
&&(and),||(or),!(not)
Key Facts
- โTruthy/falsy:
0,"",null,undefined,NaNare all falsy in JS โ treated as False in conditions - โThe
!operator negates:if (!isLoggedIn)means 'if not logged in' - โ
switch (value) { case x: ... }โ useful for many possible values - โLogical AND:
&&; logical OR:||; nullish coalescing:??
Real-World Examples
Remember
Always use === instead of == in JavaScript. The triple equals checks both value and type, preventing a whole class of subtle bugs that beginners (and even pros) fall into with ==.
Quick Quiz
What do we put inside if ()?