Decisions and repetition
The JavaScript if/else conditional
Learn how the JavaScript if/else conditional works, from truthy and falsy expressions to omitting the block for a single statement and nesting else if blocks.
An if statement picks one path based on a condition. JavaScript evaluates the expression, treats it as true or false, and runs the matching block.
This always runs because the condition is literally true:
if (true) {
//do something
}
This never runs:
if (false) {
//do something (? never ?)
}
With a single statement you can skip the block:
if (true) doSomething()
Truthy and falsy
The condition does not need to be true or false. JavaScript converts the value using truthiness rules.
Numbers are truthy except 0 and NaN. Strings are truthy except ''. Objects and arrays are truthy. null and undefined are falsy.
Run this to see the pattern:
if ('hello') console.log('string is truthy')
if (0) console.log('never runs')
The first line prints. The second does not.
Else
Add else for the false branch:
if (true) {
//do something
} else {
//do something else
}
else accepts one statement, so you can nest another conditional:
if (a === true) {
//do something
} else if (b === true) {
//do something else
} else {
//fallback
}
Read conditions from top to bottom. The first match wins. Put the most specific checks first and broad fallbacks last.
Blocks create scope for let and const. A variable declared inside if is not visible outside it.
You can chain else if as many times as you need. Keep each branch small. When a branch grows past a few lines, extract a function with a descriptive name.
Ternary expressions fit simple assignments. Multi-step branches belong in if/else blocks where you can log and debug each path.
My advice: prefer explicit comparisons when the input might be 0 or ''. if (count) treats zero as false even when zero is valid data.
Try this: write an if/else that sets label to 'empty' for '', 'zero' for 0, and 'ok' for any other string. Log each case and confirm the branch you expected.
Lesson completed