Skip to main content

if/else

Same concept as Python, different syntax:
Two differences: curly braces instead of colons and indentation, and else if instead of elif.

Conditions must be in parentheses

Truthy and falsy values

JavaScript evaluates any value as true or false in a condition. This matters more than you’d expect. Falsy values (evaluate to false):
Everything else is truthy — including some surprises:
Empty arrays [] and empty objects {} are truthy in JavaScript. This is different from Python, where empty lists and dicts are falsy. To check if an array is empty, use array.length === 0.

Practical use of truthy/falsy

Ternary operator

A one-line if/else. You’ll use this constantly in React for conditional rendering.
The syntax: condition ? valueIfTrue : valueIfFalse

Ternary in React

This is where the ternary operator really shines:
Keep ternaries simple — one condition, two outcomes. If you need more complex logic, use an if/else block or extract the logic into a separate function.

Logical operators

&& (AND) — short-circuit rendering

Returns the second value if the first is truthy. Otherwise returns the first.
In React, && is the most common way to conditionally show something:

|| (OR) — fallback values

Returns the first truthy value.
|| treats 0, "", and false as falsy — so 0 || 5 returns 5, not 0. If you need to only fall back on null/undefined, use ?? instead.

?? (nullish coalescing) — null/undefined fallback

Returns the right side only if the left is null or undefined. Doesn’t trigger on 0, "", or false.
Use ?? when a value of 0, "", or false is valid and shouldn’t be replaced. Use || when you want any falsy value to trigger the fallback.

switch statements

For multiple conditions against the same value:
Don’t forget break after each case. Without it, execution “falls through” to the next case. This is a common source of bugs.

What’s next?

You can make decisions with conditionals. Now let’s learn how to repeat actions with loops.

Loops

Iterate over data with for loops and more