JavaScript: Conditionals
JavaScript Conditional Statements
1 Overview
📘 Conditionals
Conditional statements allow you to execute different code blocks based on different conditions. JavaScript provides several ways to implement conditional logic: the if statement for basic conditions, else if for multiple conditions, the ternary operator ? for concise conditional assignments, and the switch statement for handling multiple specific values. These control structures are fundamental for creating dynamic and responsive programs.
2 The “if” Statement
The if statement evaluates a condition in parentheses and, if the result is true, executes a block of code.
2.1 Multiple Statements
If you want to execute more than one statement, wrap your code block inside curly braces:
3 Boolean Conversion
The if (...) statement evaluates the expression in its parentheses and converts the result to a boolean.
Falsy values (become false): - 0 - "" (empty string) - null - undefined - NaN
Truthy values (become true): - All other values
3.1 Examples
4 The “else” Clause
The if statement may contain an optional else block. It executes when the condition is falsy.
5 Several Conditions: “else if”
Sometimes we need to test several variants of a condition. The else if clause lets us do that.
There can be multiple else if blocks. The final else is optional.
6 Conditional (Ternary) Operator ‘?’
Sometimes we need to assign a variable depending on a condition. The ternary operator provides a shorter and simpler way.
6.1 Syntax
- The
conditionis evaluated - If it’s truthy,
value1is returned - Otherwise,
value2is returned
6.2 Example
Since the comparison itself returns true/false, we can simplify:
6.3 Multiple ‘?’
A sequence of question mark operators can return a value that depends on more than one condition:
This is equivalent to:
Use ternary operator for assignment, not replacement of if
The ternary operator is great for conditional assignments but can reduce readability when used for complex logic. Use if/else for better clarity in such cases.
7 The “switch” Statement
The switch statement can replace multiple if checks. It provides a more descriptive way to compare a value with multiple variants.
7.1 Syntax
7.2 How it Works
- The value of
xis checked for strict equality (===) with the value from the firstcase - If equality is found,
switchexecutes the code starting from thatcaseuntil the nearestbreak - If no case is matched, the
defaultcode is executed (if it exists)
7.3 Example
7.4 The Importance of break
If there is no break, execution continues with the next case without any checks (fall-through):
This will output: - “Exactly!” - “Too big” - “I don’t know such values”
7.5 Grouping Cases
Several variants of case which share the same code can be grouped:
Now both 3 and 5 show the same message.
7.6 Type Matters
The equality check in switch is always strict (===). The values must be of the same type to match.
8 Comparison: if vs switch
8.1 Use if/else when:
- You have complex conditions
- You need to check ranges (e.g.,
age > 18) - You have boolean logic
8.2 Use switch when:
- You have multiple specific values to check
- You want cleaner code for many equality checks
- You need to group similar cases
9 Examples
9.1 Example 1: Grade Calculator
9.2 Example 2: Day of Week
let day = prompt('Enter a day number (1-7):', '');
day = Number(day);
switch (day) {
case 1:
alert('Monday');
break;
case 2:
alert('Tuesday');
break;
case 3:
alert('Wednesday');
break;
case 4:
alert('Thursday');
break;
case 5:
alert('Friday');
break;
case 6:
case 7:
alert('Weekend!');
break;
default:
alert('Invalid day number');
}9.3 Example 3: Ternary Operator
9.4 Example 4: Login System
let username = prompt('Enter username:', '');
let password = prompt('Enter password:', '');
if (username === 'admin' && password === 'secret123') {
alert('Welcome, Admin!');
} else if (username === 'admin') {
alert('Wrong password!');
} else if (password === 'secret123') {
alert('Wrong username!');
} else {
alert('Invalid credentials!');
}9.5 Example 5: Calculator with Switch
let num1 = Number(prompt('Enter first number:', ''));
let operator = prompt('Enter operator (+, -, *, /):', '');
let num2 = Number(prompt('Enter second number:', ''));
let result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 !== 0) {
result = num1 / num2;
} else {
alert('Cannot divide by zero!');
result = 'Error';
}
break;
default:
alert('Invalid operator!');
result = 'Error';
}
if (result !== 'Error') {
alert(`Result: ${num1} ${operator} ${num2} = ${result}`);
}9.6 Example 6: Season Checker
let month = prompt('Enter month (1-12):', '');
month = Number(month);
switch (month) {
case 12:
case 1:
case 2:
alert('Winter');
break;
case 3:
case 4:
case 5:
alert('Spring');
break;
case 6:
case 7:
case 8:
alert('Summer');
break;
case 9:
case 10:
case 11:
alert('Fall');
break;
default:
alert('Invalid month!');
}10 Summary
- Use
ifto test conditions and execute code blocks - Use
elseto handle the opposite condition - Use
else ifto test multiple conditions sequentially - The ternary operator
? :is a concise way to assign values based on conditions - Use
switchfor multiple equality checks against a single value switchuses strict equality (===)- Always use
breakinswitchunless you want fall-through behavior - Group similar
casestatements to share code - Choose
if/elsefor complex conditions,switchfor multiple specific values