JavaScript if...else Conditional Statements Example
Direct Answer & Overview
JavaScript conditional statements execute distinct blocks of code based on whether a specified condition evaluates to truthy or falsy. The if...else syntax provides structured branching control flow across all ECMAScript environments.
JavaScript Source Code
const age = 20;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}How does this JavaScript code work?
The `if...else` statement evaluates an expression inside parentheses. If the expression evaluates to a truthy value (any value except `false`, `0`, `""`, `null`, `undefined`, or `NaN`), the subsequent block executes. Otherwise, control flows to an optional `else` or `else if` clause. Always use strict equality (`===`) rather than loose equality (`==`) to avoid unintended type coercion bugs.
What is the expected terminal output?
Executing this code in JS CodeLab produces the following stdout sequence in the developer console:
AdultCommon mistakes to avoid
- !Using a single equals sign (=) for assignment inside an if condition instead of strict comparison (===).
- !Using loose equality (==), which performs implicit type coercion and leads to subtle falsy value bugs.
- !Omitting curly braces for single-line if statements, which creates security and maintainability risks.
- !Neglecting truthy and falsy edge cases, such as empty arrays [] or empty objects {} evaluating to truthy.
Frequently Asked Questions
What is the difference between == and === in JavaScript?
The strict equality operator (===) compares both value and datatype without coercion. The loose equality operator (==) attempts implicit type conversion before comparing, which frequently yields unexpected truthy results.
What values are considered falsy in JavaScript?
There are exactly eight falsy values in JavaScript: false, 0, -0, 0n (BigInt), '' (empty string), null, undefined, and NaN. All other values, including empty arrays [] and objects {}, are truthy.
When should I use a ternary operator instead of if-else?
Use the ternary operator (condition ? trueVal : falseVal) for concise inline value assignments. Use if-else blocks when executing multi-statement logic or side effects.