JavaScript: conditionals
Conditional statements choose which code runs based on whether an expression is true or false.
What you will learn
- How
if,else if, andelsework - How strict comparison and boolean values affect a branch
- When a
switchstatement is useful
Minimal example
const score = 72;
if (score >= 80) {
console.log('Great');
} else if (score >= 60) {
console.log('Pass');
} else {
console.log('Try again');
}Conditions are evaluated from top to bottom. Once a matching branch runs, the remaining branches are skipped.
Common mistakes
- Prefer
===and!==when comparing values without implicit type conversion. - Remember that empty strings,
0,false,null, andundefinedare falsy. - Use braces even for short branches so later edits do not change the intended scope.