JavaScript Conditional Statements
Learn how JavaScript makes decisions using if, else, else if, switch statements, comparison operators, logical operators, nested conditions, and the ternary operator.
Introduction
Programs do not always execute every instruction in exactly the same way. Real applications need to make decisions and perform different actions depending on the current situation.
A login system allows access only when the entered credentials are correct. An online store applies free delivery only when the order amount reaches a certain value. A game ends when the player loses all remaining lives.
JavaScript uses conditional statements to make these decisions. A condition is evaluated, and JavaScript chooses which block of code should execute.
Conditional statements are one of the most important foundations of programming because they allow applications to react intelligently to data, users, events, and changing situations.
- What conditional statements are.
- Why programs need decision-making.
- How boolean conditions control execution.
- How comparison operators create conditions.
- How the if statement works.
- How the else statement works.
- How else if handles multiple possibilities.
- Why the order of conditions matters.
- How nested conditions work.
- How the logical AND operator works.
- How the logical OR operator works.
- How the logical NOT operator works.
- How to combine multiple conditions.
- What truthy and falsy values are.
- The difference between strict and loose comparison.
- How the switch statement works.
- How case, break, and default work.
- What switch fall-through means.
- When to use if...else and when to use switch.
- How the ternary operator works.
- Why deeply nested ternary expressions should be avoided.
- How short-circuit evaluation works.
- How conditions are used for form validation.
- How to build complete decision-making programs.
What are Conditional Statements?
Conditional statements allow a program to execute different blocks of code depending on whether a condition is true or false.
IF condition is true │ ▼Execute one action
ELSE │ ▼Execute another actionconst age = 20;
if (age >= 18) { console.log('You are eligible to vote.');}Click Run to see what this code prints.
The expression age >= 18 produces a boolean value. Because the result is true, the code inside the if block executes.
- A condition asks a question.
- The answer is treated as true or false.
- JavaScript chooses what code to execute.
- Different results can produce different actions.
Why Do We Need Conditions?
Without conditional statements, a program would execute the same instructions every time. It could not react differently to different users, values, or situations.
Authentication
Allow access when credentials are correct and reject invalid login attempts.
Validation
Check whether required form fields contain valid information.
Shopping
Apply discounts, delivery charges, and offers based on order conditions.
Games
React to scores, player health, levels, lives, and game states.
User Interfaces
Show or hide content depending on application state.
Permissions
Allow different actions for administrators, users, and guests.
Real-World Analogy
Think about a traffic signal. A driver performs a different action depending on the current signal color.
Traffic Signal │ ▼┌─────────────┐│ Is it RED? │└──────┬──────┘ │ Yes │ ▼ STOP
Otherwise │ ▼┌──────────────┐│ Is it YELLOW?│└──────┬───────┘ │ Yes │ ▼ PREPARE
Otherwise │ ▼ GOconst signal = 'red';
if (signal === 'red') { console.log('Stop');} else if (signal === 'yellow') { console.log('Prepare');} else { console.log('Go');}Click Run to see what this code prints.
Decision-Making Flow
Conditional execution usually begins with a condition. JavaScript evaluates the condition and follows one of the available execution paths.
START │ ▼ ┌─────────────┐ │ Condition │ └──────┬──────┘ │ ┌─────┴─────┐ │ │ true false │ │ ▼ ▼┌────────────┐ ┌────────────┐│ Action A │ │ Action B │└─────┬──────┘ └──────┬─────┘ │ │ └───────┬───────┘ ▼ CONTINUEOnly the code belonging to the selected path is executed.
Boolean Conditions
Conditions are based on values that JavaScript interprets as true or false.
const isLoggedIn = true;const isAdmin = false;
if (isLoggedIn) { console.log('Welcome back!');}
if (isAdmin) { console.log('Admin panel opened.');}Click Run to see what this code prints.
The second message is not displayed because isAdmin contains false.
const score = 75;
const hasPassed = score >= 40;
console.log(hasPassed);
if (hasPassed) { console.log('Student passed.');}Click Run to see what this code prints.
Comparison Operators
Comparison operators compare values and produce true or false. They are frequently used to create conditions.
Operator Meaning----------------------------------------== Equal value=== Equal value and type!= Not equal value!== Not equal value or type> Greater than< Less than>= Greater than or equal to<= Less than or equal toconsole.log(10 > 5);console.log(10 < 5);console.log(10 >= 10);console.log(5 <= 10);console.log(10 === 10);console.log(10 !== 20);Click Run to see what this code prints.
- age >= 18 checks minimum age.
- score < 40 checks a failing score.
- password === savedPassword checks exact equality.
- quantity !== 0 checks that quantity is not zero.
The if Statement
The if statement executes a block of code only when its condition is true.
if (condition) { // Code executes when condition is true}const temperature = 35;
if (temperature > 30) { console.log('It is a hot day.');}Click Run to see what this code prints.
const temperature = 20;
if (temperature > 30) { console.log('It is a hot day.');}
console.log('Program completed.');Click Run to see what this code prints.
Fix the condition so the message only logs when the score is 50 or higher.
The message inside the if block is skipped because the condition is false. Execution continues after the conditional block.
How if Works
START │ ▼ ┌─────────────┐ │ Condition │ └──────┬──────┘ │ ┌─────┴─────┐ │ │ true false │ │ ▼ │┌──────────────┐ ││ Execute Code │ │└──────┬───────┘ │ │ │ └─────┬─────┘ ▼ CONTINUEconst balance = 5000;
console.log('Checking balance...');
if (balance >= 1000) { console.log('Withdrawal allowed.');}
console.log('Transaction completed.');Click Run to see what this code prints.
if with Variables
Conditions commonly compare variables containing application data.
const age = 21;
if (age >= 18) { console.log('You are an adult.');}Click Run to see what this code prints.
const stock = 5;
if (stock > 0) { console.log('Product is available.');}Click Run to see what this code prints.
if with User Input
Conditional statements become especially useful when they process input received from users.
const age = Number(prompt('Enter your age:'));
if (age >= 18) { alert('You are eligible to vote.');}Click Run to see what this code prints.
Click Run to see what this code prints.
The else Statement
The else statement provides an alternative block of code when the if condition is false.
if (condition) { // Executes when condition is true} else { // Executes when condition is false}const age = 16;
if (age >= 18) { console.log('You can vote.');} else { console.log('You cannot vote yet.');}Click Run to see what this code prints.
const number = 7;
if (number % 2 === 0) { console.log('Even number');} else { console.log('Odd number');}Click Run to see what this code prints.
if...else Flow
START │ ▼ ┌─────────────┐ │ Condition │ └──────┬──────┘ │ ┌─────┴─────┐ │ │ true false │ │ ▼ ▼┌────────────┐ ┌────────────┐│ if Block │ │ else Block │└─────┬──────┘ └──────┬─────┘ │ │ └───────┬───────┘ ▼ CONTINUE- If the condition is true, the if block executes.
- If the condition is false, the else block executes.
- Both blocks do not execute during the same decision.
The else if Statement
The else if statement checks additional conditions when the previous conditions were false.
if (condition1) { // First condition is true} else if (condition2) { // Second condition is true} else { // No previous condition is true}const temperature = 25;
if (temperature > 35) { console.log('Very hot');} else if (temperature > 25) { console.log('Warm');} else if (temperature > 15) { console.log('Pleasant');} else { console.log('Cold');}Click Run to see what this code prints.
This chain misclassifies cold temperatures as pleasant — fix the comparison so a temperature of 10 correctly logs 'Cold'.
Multiple Conditions
An else if chain allows a program to choose one result from several possibilities.
const marks = 82;
if (marks >= 90) { console.log('Grade A+');} else if (marks >= 80) { console.log('Grade A');} else if (marks >= 70) { console.log('Grade B');} else if (marks >= 60) { console.log('Grade C');} else if (marks >= 40) { console.log('Grade D');} else { console.log('Failed');}Click Run to see what this code prints.
marks >= 90 ? │ ┌──┴──┐ Yes No │ │ A+ ▼ marks >= 80 ? │ ┌──┴──┐ Yes No │ │ A ▼ Continue CheckingOrder of Conditions
JavaScript checks an else if chain from top to bottom. As soon as one condition is true, its block executes and the remaining conditions are skipped.
const marks = 95;
if (marks >= 40) { console.log('Passed');} else if (marks >= 90) { console.log('Excellent');}Click Run to see what this code prints.
The result is logically incomplete because marks >= 40 is already true. JavaScript never reaches the more specific marks >= 90 condition.
const marks = 95;
if (marks >= 90) { console.log('Excellent');} else if (marks >= 40) { console.log('Passed');} else { console.log('Failed');}Click Run to see what this code prints.
The broader condition is checked before the more specific one, so 95 points always logs 'Passed'. Reorder the conditions so it correctly logs 'Excellent'.
- Conditions are checked from top to bottom.
- The first true branch is selected.
- Later branches are skipped.
- Place more specific conditions before broader conditions.
Nested if Statements
An if statement can be placed inside another if statement. This is called nesting.
if (condition1) { if (condition2) { // Executes when both conditions are true }}const isLoggedIn = true;const role = 'admin';
if (isLoggedIn) { console.log('User is logged in.');
if (role === 'admin') { console.log('Admin panel opened.'); }}Click Run to see what this code prints.
const age = 25;const hasLicense = true;
if (age >= 18) { if (hasLicense) { console.log('You can drive.'); } else { console.log('You need a driving license.'); }} else { console.log('You are too young to drive.');}Click Run to see what this code prints.
Fix the inner condition so a licensed adult correctly logs 'You can drive.'
- Nesting is useful when one decision depends on another.
- Too many nested levels make code difficult to read.
- Logical operators can often combine related conditions.
- Use early returns in functions when appropriate.
Logical AND (&&)
The logical AND operator returns a truthy result only when both conditions are truthy.
Condition A Condition B A && B------------------------------------------true true truetrue false falsefalse true falsefalse false falseconst age = 25;const hasLicense = true;
if (age >= 18 && hasLicense) { console.log('You can drive.');}Click Run to see what this code prints.
const username = 'admin';const password = '1234';
if ( username === 'admin' && password === '1234') { console.log('Login successful.');} else { console.log('Invalid credentials.');}Click Run to see what this code prints.
Fix the condition so login only succeeds when both the username and password are correct.
Logical OR (||)
The logical OR operator produces a truthy result when at least one condition is truthy.
Condition A Condition B A || B------------------------------------------true true truetrue false truefalse true truefalse false falseconst role = 'admin';
if ( role === 'admin' || role === 'manager') { console.log('Access granted.');}Click Run to see what this code prints.
const day = 'Sunday';
if ( day === 'Saturday' || day === 'Sunday') { console.log('It is the weekend.');}Click Run to see what this code prints.
Fix the condition so it correctly identifies both Saturday and Sunday as the weekend.
Logical NOT (!)
The logical NOT operator reverses the truthiness of a value.
Value !Value----------------true falsefalse trueconst isLoggedIn = false;
if (!isLoggedIn) { console.log('Please log in.');}Click Run to see what this code prints.
const isOutOfStock = false;
if (!isOutOfStock) { console.log('Product is available.');}Click Run to see what this code prints.
Fix the condition so the message logs only when the product is NOT out of stock.
Combining Conditions
Complex decisions can combine comparison and logical operators.
const age = 30;const salary = 50000;const hasGoodCredit = true;
if ( age >= 21 && salary >= 30000 && hasGoodCredit) { console.log('Loan application eligible.');} else { console.log('Loan application not eligible.');}Click Run to see what this code prints.
const role = 'editor';const isActive = true;
if ( isActive && ( role === 'admin' || role === 'editor' )) { console.log('Dashboard access granted.');}Click Run to see what this code prints.
- Parentheses make complex conditions easier to understand.
- Group related OR conditions together.
- Keep each important condition readable.
- Break extremely complex conditions into descriptive variables.
Truthy and Falsy Values
JavaScript conditions do not require an actual boolean value. JavaScript can convert other values into true or false when evaluating a condition.
const userName = 'Rahul';
if (userName) { console.log('Username exists.');}Click Run to see what this code prints.
const userName = '';
if (userName) { console.log('Username exists.');} else { console.log('Username is empty.');}Click Run to see what this code prints.
Falsy Values
Falsy values are values that JavaScript treats as false in a boolean context.
false0-00n''""``nullundefinedNaNif (0) { console.log('Runs');} else { console.log('0 is falsy');}
if ('') { console.log('Runs');} else { console.log('Empty string is falsy');}Click Run to see what this code prints.
Truthy Values
Most values that are not falsy are treated as truthy.
'Hello''0''false'42-10[]{}function () {}if ('Hello') { console.log('Non-empty string is truthy');}
if ([]) { console.log('Empty array is truthy');}
if ({}) { console.log('Empty object is truthy');}Click Run to see what this code prints.
- The number 0 is falsy.
- The string "0" is truthy.
- The boolean false is falsy.
- The string "false" is truthy.
- An empty string is falsy.
- An empty array is truthy.
- An empty object is truthy.
Strict vs Loose Comparison
JavaScript provides loose equality and strict equality operators. Strict equality is generally preferred because it compares both value and data type.
console.log(5 == '5');Click Run to see what this code prints.
console.log(5 === '5');Click Run to see what this code prints.
Fix the comparison so it strictly checks both value and type.
Expression Result-------------------------5 == '5' true5 === '5' false
0 == false true0 === false false- Use === instead of == in most cases.
- Use !== instead of != in most cases.
- Strict comparison avoids automatic type conversion.
- Strict comparison makes conditions more predictable.
The switch Statement
The switch statement compares one expression against multiple possible values. It can be easier to read than a long else if chain when checking exact values.
switch (expression) { case value1: // Code break;
case value2: // Code break;
default: // Default code}const day = 2;
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');}Click Run to see what this code prints.
How switch Works
Expression │ ▼ Compare with Case 1 │ │ Match No Match │ │ ▼ ▼ Execute Compare with Case 1 Case 2 │ │ break Continue │ ▼ ENDJavaScript evaluates the switch expression once and compares its result against each case using strict comparison behavior.
The case Keyword
Each case represents one possible value that can match the switch expression.
const role = 'editor';
switch (role) { case 'admin': console.log('Full access'); break;
case 'editor': console.log('Content access'); break;
case 'user': console.log('Basic access'); break;}Click Run to see what this code prints.
The break Keyword
The break keyword stops the switch statement after a matching case has executed.
const color = 'green';
switch (color) { case 'red': console.log('Stop'); break;
case 'green': console.log('Go'); break;
case 'yellow': console.log('Prepare'); break;}Click Run to see what this code prints.
Add the missing break statement so only 'Stop' is logged for a red light, without falling through to the next case.
The default Keyword
The default block executes when no case matches the switch expression.
const browser = 'Unknown';
switch (browser) { case 'Chrome': console.log('Google Chrome'); break;
case 'Firefox': console.log('Mozilla Firefox'); break;
default: console.log('Other browser');}Click Run to see what this code prints.
Multiple Cases
Multiple case labels can share the same block of code.
const day = 'Sunday';
switch (day) { case 'Saturday': case 'Sunday': console.log('Weekend'); break;
case 'Monday': case 'Tuesday': case 'Wednesday': case 'Thursday': case 'Friday': console.log('Weekday'); break;
default: console.log('Invalid day');}Click Run to see what this code prints.
Switch Fall-Through
If break is omitted, execution continues into the following cases. This behavior is called fall-through.
const number = 1;
switch (number) { case 1: console.log('One');
case 2: console.log('Two');
case 3: console.log('Three');}Click Run to see what this code prints.
- Without break, execution continues into later cases.
- Fall-through is sometimes intentional.
- Accidental fall-through is a common beginner mistake.
- Use break unless shared execution is deliberately required.
if...else vs switch
Feature if...else switch----------------------------------------------------------Ranges Excellent Not idealComplex conditions Excellent LimitedLogical operators Excellent Not directExact values Good ExcellentMany exact options Can become long Often cleanerExpression checked Can vary Usually one valueif (score >= 90) { console.log('A');} else if (score >= 80) { console.log('B');}switch (role) { case 'admin': console.log('Admin'); break;
case 'user': console.log('User'); break;}- Use if for ranges.
- Use if for complex logical conditions.
- Use switch for many exact values of one expression.
- Choose the structure that makes the logic easiest to understand.
Ternary Operator
The ternary operator provides a compact way to choose between two values based on a condition.
condition ? valueIfTrue : valueIfFalseconst age = 20;let message;
if (age >= 18) { message = 'Adult';} else { message = 'Minor';}
console.log(message);Click Run to see what this code prints.
const age = 20;
const message = age >= 18 ? 'Adult' : 'Minor';
console.log(message);Click Run to see what this code prints.
const isLoggedIn = true;
console.log( `Status: ${isLoggedIn ? 'Online' : 'Offline'}`);Click Run to see what this code prints.
The ternary values are swapped — fix it so the status correctly shows 'Offline' when isLoggedIn is false.
Nested Ternary
A ternary expression can contain another ternary expression, but deeply nested ternaries quickly become difficult to understand.
const score = 75;
const result = score >= 80 ? 'Excellent' : score >= 40 ? 'Passed' : 'Failed';
console.log(result);Click Run to see what this code prints.
- Simple ternary expressions are concise.
- Nested ternaries can become difficult to scan.
- Use if...else when multiple decisions require explanation.
- Readability is more important than writing fewer lines.
Short-Circuit Evaluation
Logical operators may stop evaluating expressions as soon as the final result is already known. This behavior is called short-circuit evaluation.
const isLoggedIn = true;
isLoggedIn && console.log('Welcome back!');Click Run to see what this code prints.
const userName = '';
const displayName = userName || 'Guest';
console.log(displayName);Click Run to see what this code prints.
A && B
If A is falsy:B does not need to be evaluated
A || B
If A is truthy:B does not need to be evaluated- && can conditionally execute an expression.
- || can provide a fallback for falsy values.
- Logical operators return values, not always actual booleans.
- Use clear if statements when short-circuit code becomes difficult to understand.
Conditional Form Validation
Conditional statements are commonly used to validate form input before data is processed.
<input type="text" id="userName" placeholder="Enter username">
<input type="number" id="age" placeholder="Enter age">
<button id="submitButton"> Submit</button>
<p id="message"></p>const userNameInput = document.getElementById('userName');
const ageInput = document.getElementById('age');
const submitButton = document.getElementById('submitButton');
const message = document.getElementById('message');
submitButton.addEventListener('click', function () { const userName = userNameInput.value.trim();
const age = Number(ageInput.value);
if (userName === '') { message.textContent = 'Username is required.';
} else if ( Number.isNaN(age) || age <= 0 ) { message.textContent = 'Enter a valid age.';
} else if (age < 18) { message.textContent = 'You must be at least 18 years old.';
} else { message.textContent = `Welcome, ${userName}!`; }});Click Run to see what this code prints.
Click Run to see what this code prints.
Click Run to see what this code prints.
Click Run to see what this code prints.
Complete Grade Calculator
The following example receives marks, validates the input, determines a grade, and displays the result.
<div class="grade-calculator"> <h2>Grade Calculator</h2>
<input type="number" id="marks" placeholder="Enter marks from 0 to 100" >
<button id="calculateButton"> Calculate Grade </button>
<p id="result"></p></div>const marksInput = document.getElementById('marks');
const calculateButton = document.getElementById('calculateButton');
const result = document.getElementById('result');
calculateButton.addEventListener('click', function () { const marks = Number(marksInput.value);
let grade;
if ( Number.isNaN(marks) || marks < 0 || marks > 100 ) { result.textContent = 'Please enter marks between 0 and 100.';
return; }
if (marks >= 90) { grade = 'A+'; } else if (marks >= 80) { grade = 'A'; } else if (marks >= 70) { grade = 'B'; } else if (marks >= 60) { grade = 'C'; } else if (marks >= 40) { grade = 'D'; } else { grade = 'F'; }
const status = marks >= 40 ? 'Passed' : 'Failed';
result.textContent = `Grade: ${grade} | Status: ${status}`;});Click Run to see what this code prints.
Click Run to see what this code prints.
User Enters Marks │ ▼ Convert to Number │ ▼ Validate Marks │ ┌──────┴──────┐ │ │ Invalid Valid │ │ ▼ ▼ Show Error Check Ranges │ ▼ Determine Grade │ ▼ Determine Status │ ▼ Show ResultComplete Login Example
This example combines form input, validation, logical operators, and conditional output.
<div class="login-box"> <h2>Login</h2>
<input type="text" id="username" placeholder="Username" >
<input type="password" id="password" placeholder="Password" >
<button id="loginButton"> Login </button>
<p id="message"></p></div>const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const loginButton = document.getElementById('loginButton');
const message = document.getElementById('message');
loginButton.addEventListener('click', function () { const username = usernameInput.value.trim();
const password = passwordInput.value;
if ( username === '' || password === '' ) { message.textContent = 'Please enter username and password.';
return; }
if ( username === 'admin' && password === '1234' ) { message.textContent = 'Login successful!';
} else { message.textContent = 'Invalid username or password.'; }});Click Run to see what this code prints.
Click Run to see what this code prints.
Click Run to see what this code prints.
Conditional Execution Flow
A complete decision-making process often receives input, validates it, evaluates one or more conditions, executes the selected branch, and displays output.
┌──────────────────────┐│ INPUT ││ ││ User Data ││ Form Values ││ Application State │└──────────┬───────────┘ │ ▼┌──────────────────────┐│ VALIDATION ││ ││ Is Input Valid? │└──────────┬───────────┘ │ ┌────┴────┐ │ │ No Yes │ │ ▼ ▼ Show Error Evaluate Conditions │ ▼ ┌────────────────┐ │ Select Branch │ │ │ │ if │ │ else if │ │ else │ │ switch │ └───────┬────────┘ │ ▼ Execute Action │ ▼ Display OutputReal-World Applications
Conditional statements are used in almost every interactive JavaScript application.
Login Systems
Check credentials and determine whether access should be granted.
User Roles
Display different features for administrators, editors, users, and guests.
E-Commerce
Apply discounts, calculate delivery fees, and check product availability.
Form Validation
Check required fields, formats, age restrictions, and valid ranges.
Games
Control levels, health, scores, lives, rewards, and game-over states.
Weather Apps
Display different messages and icons based on weather conditions.
Dashboards
Change information and controls based on data and user selections.
Notifications
Display success, warning, error, and informational messages.
Common Beginner Mistakes
- Using = instead of === inside a condition.
- Using == when strict comparison is more appropriate.
- Forgetting parentheses around the condition.
- Forgetting braces around code blocks.
- Adding a semicolon immediately after an if condition.
- Writing conditions in the wrong order.
- Placing broad conditions before specific conditions.
- Forgetting that only the first matching else if branch executes.
- Creating unnecessary nested if statements.
- Using && when || is required.
- Using || when && is required.
- Forgetting that ! reverses truthiness.
- Assuming every condition must contain an explicit boolean.
- Forgetting that 0 is falsy.
- Forgetting that an empty string is falsy.
- Assuming the string "false" is falsy.
- Assuming an empty array is falsy.
- Assuming an empty object is falsy.
- Comparing a number and string with strict equality without converting input.
- Forgetting that form values are usually strings.
- Using switch for complicated ranges.
- Forgetting break inside switch cases.
- Creating accidental switch fall-through.
- Forgetting the default case when unmatched values need handling.
- Using a long switch when a simpler structure would be clearer.
- Using deeply nested ternary expressions.
- Using short-circuit expressions when an if statement would be clearer.
- Writing extremely long conditions in one line.
- Not using parentheses to clarify complex logical expressions.
- Processing user input before validation.
- Failing to handle invalid or missing input.
// ❌ Assignment instead of comparison// if (age = 18) { }
// ❌ Semicolon ends the if statement// if (age >= 18);// {// console.log('Adult');// }
// ❌ Wrong condition order// if (marks >= 40) {// console.log('Passed');// } else if (marks >= 90) {// console.log('Excellent');// }
// ❌ Missing break// switch (day) {// case 1:// console.log('Monday');// case 2:// console.log('Tuesday');// }
// ❌ Difficult nested ternary// const result = a ? b ? c : d : e ? f : g;Best Practices
- Use descriptive variable names in conditions.
- Prefer strict equality === over loose equality ==.
- Prefer strict inequality !== over loose inequality !=.
- Keep conditions simple and readable.
- Use parentheses to clarify complex logical expressions.
- Place more specific conditions before broader conditions.
- Remember that else if chains are checked from top to bottom.
- Use if when checking ranges.
- Use if when conditions require logical operators.
- Use switch when comparing one expression against many exact values.
- Include break in switch cases unless fall-through is intentional.
- Use default when unmatched values require handling.
- Use ternary expressions for simple two-value decisions.
- Avoid deeply nested ternary expressions.
- Avoid unnecessary nesting.
- Combine related conditions with logical operators when it improves clarity.
- Break complex conditions into descriptive boolean variables.
- Validate input before making business decisions.
- Convert form input into the correct data type before comparison.
- Remember that input values are usually strings.
- Use Number.isNaN() when validating numeric conversion.
- Handle empty and missing values explicitly.
- Understand truthy and falsy behavior.
- Do not assume empty arrays or objects are falsy.
- Use short-circuit evaluation only when the intent remains clear.
- Add comments when business rules are not obvious.
- Keep conditional blocks focused on one responsibility.
- Use early returns in functions to reduce deep nesting when appropriate.
- Test boundary values such as exactly 18, exactly 40, or exactly 100.
- Test both true and false execution paths.
const age = 25;const hasLicense = true;const isSuspended = false;
const isOldEnough = age >= 18;
const canLegallyDrive = isOldEnough && hasLicense && !isSuspended;
if (canLegallyDrive) { console.log('Driving allowed.');} else { console.log('Driving not allowed.');}Click Run to see what this code prints.
Frequently Asked Questions
A conditional statement allows JavaScript to execute different code depending on whether a condition is true or false.
A condition is an expression evaluated for truthiness to determine which code should execute.
It executes a block of code when its condition is truthy.
It provides an alternative block when the previous if condition is falsy.
It checks another condition when all previous conditions in the chain were false.
Yes. An if statement can contain multiple else if branches.
No. Only the first matching branch in the chain executes.
Conditions are checked from top to bottom, and later conditions are skipped after the first matching branch.
It is an if statement placed inside another conditional block.
The logical AND operator requires both operands to be truthy for the combined condition to be truthy.
The logical OR operator produces a truthy result when at least one operand is truthy.
The logical NOT operator reverses the truthiness of a value.
A truthy value is a value JavaScript treats as true in a boolean context.
A falsy value is a value JavaScript treats as false in a boolean context.
The number 0 is falsy.
The non-empty string "0" is truthy.
An empty string is falsy.
No. An empty array is truthy.
No. An empty object is truthy.
== allows type coercion, while === requires both value and type to match.
Strict equality === is generally preferred.
A switch statement compares one expression against multiple exact case values.
A case defines one possible matching value.
break stops execution from continuing into later cases.
Execution continues into following cases. This is called fall-through.
It executes when no case matches.
Use if for ranges, complex comparisons, and logical conditions.
Use switch when comparing one expression against many exact values.
It is a compact conditional expression written as condition ? valueIfTrue : valueIfFalse.
Simple nesting is possible, but deeply nested ternaries should usually be replaced with clearer conditional statements.
It is when JavaScript stops evaluating a logical expression because the final result is already known.
Form values are usually strings, so conversion is required when numeric comparison or calculation is intended.
Use logical operators, descriptive boolean variables, or early returns in functions when appropriate.
Key Takeaways
- Conditional statements allow programs to make decisions.
- Conditions are evaluated based on truthiness.
- Comparison operators commonly create boolean conditions.
- The if statement executes code when a condition is truthy.
- The else statement handles the alternative path.
- The else if statement checks additional conditions.
- Only the first matching branch of an else if chain executes.
- Condition order matters.
- Specific conditions should usually come before broader conditions.
- Conditional statements can be nested.
- Excessive nesting should be avoided.
- The && operator requires both conditions to be truthy.
- The || operator requires at least one condition to be truthy.
- The ! operator reverses truthiness.
- Complex conditions can combine comparison and logical operators.
- Falsy values include false, 0, empty strings, null, undefined, and NaN.
- Most other values are truthy.
- Empty arrays and empty objects are truthy.
- Strict equality compares both value and type.
- Strict comparison is generally preferred.
- switch is useful for multiple exact values.
- case defines a possible switch match.
- break stops switch fall-through.
- default handles unmatched switch values.
- Multiple cases can share the same code.
- if is usually better for ranges and complex logic.
- switch is often cleaner for many exact values.
- The ternary operator is useful for simple two-value decisions.
- Deeply nested ternary expressions should be avoided.
- Logical operators support short-circuit evaluation.
- Conditions are essential for form validation.
- User input should be converted and validated before decision-making.
- Readable conditions are more important than shorter code.
Summary
Conditional statements allow JavaScript applications to make decisions. A condition is evaluated, and the result determines which block of code executes.
The if statement executes code when a condition is truthy. The else statement provides an alternative path, while else if allows multiple conditions to be checked in sequence.
Logical operators make complex decisions possible. The AND operator requires all connected conditions to be truthy, the OR operator requires at least one truthy condition, and the NOT operator reverses truthiness.
JavaScript also uses truthy and falsy values in conditions. Understanding how values such as 0, empty strings, null, arrays, and objects behave is important for writing reliable logic.
The switch statement is useful when one expression must be compared against several exact values. The case, break, and default keywords control its execution.
The ternary operator provides a concise alternative for simple two-value decisions, while short-circuit evaluation allows logical operators to control whether later expressions are evaluated.
Conditional statements are used throughout real applications for authentication, validation, permissions, shopping logic, games, dashboards, and user interface behavior.
- You understand conditional statements.
- You understand decision-making flow.
- You can create boolean conditions.
- You can use comparison operators.
- You can use the if statement.
- You can use the else statement.
- You can use else if statements.
- You understand multiple-condition chains.
- You understand why condition order matters.
- You can create nested conditions.
- You can use the logical AND operator.
- You can use the logical OR operator.
- You can use the logical NOT operator.
- You can combine complex conditions.
- You understand truthy and falsy values.
- You know the common falsy values.
- You understand strict and loose comparison.
- You can use switch statements.
- You understand case.
- You understand break.
- You understand default.
- You can combine multiple switch cases.
- You understand switch fall-through.
- You know when to use if...else or switch.
- You can use the ternary operator.
- You understand the problems with deeply nested ternaries.
- You understand short-circuit evaluation.
- You can use conditions for form validation.
- You can build complete decision-making applications.
- You are ready to learn JavaScript Loops.