Conditional constructs
1. if, else if, else
This is the main and most readable construct for branching code.
javascript
const age = 20;
if (age >= 18) {
console.log('Adult');
} else if (age >= 14) {
console.log('Teenager');
} else {
console.log('Child');
}ifchecks a conditionelse ifadds additional checkselseruns if all the previous ones did not match
The condition inside
ifis converted to a boolean value (truthy/falsy).
2. The ternary operator ? :
A short form for simple conditions.
javascript
const age = 18;
const status = age >= 18 ? 'Adult' : 'Minor';
console.log(status); // "Adult"Syntax:
condition ? value_if_true : value_if_false
You can nest several ternary operators (but be careful with readability):
javascript
const age = 25;
const group =
age < 13 ? 'child' :
age < 20 ? 'teenager' :
'adult';3. The switch statement
Convenient when there are many variants of the same expression.
javascript
const day = 3;
switch (day) {
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
case 3:
console.log('Wednesday');
break;
default:
console.log('Unknown day');
}breakprevents "falling through" into the nextcasedefaultis the equivalent ofelse
You can use grouping:
javascript
switch (day) {
case 6:
case 7:
console.log('Day off');
break;
default:
console.log('Workday');
}4. The logical operators &&, ||, ??
Sometimes if can be replaced with logical shorthand.
&&: "and" (runs the second operand if the first is true)
javascript
const isAdmin = true;
isAdmin && console.log('Welcome, admin!');If
isAdmin === true,console.logwill run.
||: "or" (returns the first truthy value)
javascript
const userName = '' || 'Guest';
console.log(userName); // "Guest"Convenient for default values.
??: "nullish coalescing" (only for null and undefined)
javascript
const userInput = null;
const value = userInput ?? 'Default';
console.log(value); // "Default"Difference from
||: it does not trigger on0,'',false.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.