JavaScript conditionals are one of the most important parts of programming. They allow a program to make decisions based on different conditions. Instead of always running the same code, JavaScript can check a situation and choose what should happen next.
For example, a website may need to show a different message when a user is logged in, display an error when a form is incomplete, or calculate a discount when an order reaches a certain amount. All of these tasks can use conditional statements.
What Are JavaScript Conditionals?
A conditional statement checks whether a condition is true or false and then executes code based on the result.
A simple conditional looks like this:
if (condition) {
// code runs when the condition is true
}
For example:
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
Here, JavaScript checks whether age >= 18 is true. Because age is 20, the condition is true, so the message is displayed.
Conditional statements are based heavily on Boolean values:
true
false
A condition does not always have to be written directly as true or false. Comparisons and logical expressions can also produce Boolean results.
Why Are Conditionals Important?
Programs need to make decisions. Without conditionals, most programs would only perform instructions in a fixed sequence.
Conditionals make JavaScript programs more flexible and interactive.
They are commonly used for:
- User authentication
- Form validation
- Access control
- Age verification
- Shopping cart calculations
- Discounts and promotions
- Game logic
- Error handling
- Navigation
- User interface changes
- Data processing
- Search and filtering
- API response handling
- Feature availability
- Business rules
For example:
let isLoggedIn = true;
if (isLoggedIn) {
console.log("Welcome back!");
}
The program behaves differently depending on the value of isLoggedIn.
The if Statement
The if statement is the simplest JavaScript conditional.
Its basic syntax is:
if (condition) {
// statements
}
Example:
let temperature = 35;
if (temperature > 30) {
console.log("It is hot today.");
}
If the condition is true, the code inside the braces executes.
If the condition is false, JavaScript skips that block.
Multiple Statements Inside if
You can place multiple statements inside an if block:
let age = 21;
if (age >= 18) {
console.log("Adult user");
console.log("Access granted");
console.log("You can continue.");
}
Curly braces are recommended even when there is only one statement. They make the code clearer and help prevent accidental errors when more code is added later.
The if...else Statement
Sometimes you need one action when a condition is true and another action when it is false.
The if...else statement handles this situation.
if (condition) {
// runs when true
} else {
// runs when false
}
Example:
let age = 16;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You are not eligible.");
}
Because age is 16, the condition is false, so the else block runs.
The if...else if...else Statement
When there are several possible conditions, you can use else if.
if (condition1) {
// first case
} else if (condition2) {
// second case
} else {
// fallback case
}
Example:
let marks = 78;
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 {
console.log("Needs improvement");
}
JavaScript checks the conditions from top to bottom. Once it finds a true condition, it executes that block and skips the remaining else if and else blocks.
Order Matters
Consider:
let marks = 95;
if (marks >= 60) {
console.log("Grade C or better");
} else if (marks >= 90) {
console.log("Grade A+");
}
The first condition is already true, so JavaScript never reaches the second condition.
A better order is:
if (marks >= 90) {
console.log("Grade A+");
} else if (marks >= 60) {
console.log("Grade C or better");
}
Specific conditions should generally come before broader conditions when their order affects the result.
Nested if Statements
An if statement can be placed inside another if statement. This is called a nested conditional.
let age = 25;
let hasID = true;
if (age >= 18) {
if (hasID) {
console.log("Access granted.");
}
}
Nested conditionals can be useful, but excessive nesting can make code difficult to read.
In many cases, logical operators can simplify nested conditions.
Instead of:
if (age >= 18) {
if (hasID) {
console.log("Access granted.");
}
}
You can write:
if (age >= 18 && hasID) {
console.log("Access granted.");
}
This is often easier to understand.
JavaScript Comparison Operators in Conditionals
Comparison operators are frequently used to create conditions.
Equal to: ==
The == operator checks equality after allowing type conversion.
console.log(5 == "5");
This produces:
true
Although it is part of JavaScript, == can sometimes produce surprising results because of type coercion.
Strictly Equal to: ===
The === operator checks both value and type.
console.log(5 === "5");
The result is:
false
In modern JavaScript, === is generally preferred when you want predictable equality checks.
Not Equal: !=
The != operator checks whether two values are different, with type conversion allowed.
5 != "5"
This is:
false
Strictly Not Equal: !==
The !== operator checks both value and type.
5 !== "5"
The result is:
true
Greater Than: >
let age = 25;
if (age > 18) {
console.log("Age is greater than 18.");
}
Less Than: <
let score = 40;
if (score < 50) {
console.log("Score is below 50.");
}
Greater Than or Equal To: >=
if (age >= 18) {
console.log("Eligible.");
}
Less Than or Equal To: <=
if (age <= 60) {
console.log("Within the limit.");
}
Logical Operators in Conditionals
Logical operators allow you to combine multiple conditions.
AND Operator: &&
The && operator requires both expressions to be truthy.
let age = 25;
let hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("You can enter.");
}
Both conditions must be satisfied.
OR Operator: ||
The || operator succeeds when at least one operand is truthy.
let isAdmin = false;
let isManager = true;
if (isAdmin || isManager) {
console.log("Access granted.");
}
Only one of the two conditions needs to be true.
NOT Operator: !
The ! operator reverses a Boolean value.
let loggedIn = false;
if (!loggedIn) {
console.log("Please log in.");
}
Since loggedIn is false, !loggedIn becomes true.
Truthy and Falsy Values
JavaScript does not require a condition to be explicitly true or false.
For example:
let name = "Dibya";
if (name) {
console.log("A name exists.");
}
A non-empty string is truthy.
JavaScript has several commonly recognized falsy values:
false
0
-0
0n
""
null
undefined
NaN
Most other values are truthy.
For example:
if ("Hello") {
console.log("This runs.");
}
An object is also truthy:
if ({}) {
console.log("Objects are truthy.");
}
An array is truthy as well:
if ([]) {
console.log("Arrays are truthy.");
}
This is important because an empty array and an empty object are not falsy in JavaScript.
Checking for a Value
A common pattern is:
let username = "Alex";
if (username) {
console.log("Username is available.");
}
This works because a non-empty string is truthy.
However, if the application needs to distinguish between different states, an explicit comparison may be clearer:
if (username !== "") {
console.log("Username is available.");
}
The best approach depends on what the program is trying to communicate.
The Ternary Operator
The conditional or ternary operator provides a short way to write a simple if...else.
Its syntax is:
condition ? valueIfTrue : valueIfFalse
Example:
let age = 20;
let message = age >= 18 ? "Adult" : "Minor";
console.log(message);
The expression before ? is evaluated. If it is truthy, the first value is selected. Otherwise, the value after : is selected.
A longer version would be:
let message;
if (age >= 18) {
message = "Adult";
} else {
message = "Minor";
}
The ternary operator is useful for short expressions.
Avoid creating deeply nested ternary expressions because they can become difficult to read.
Nested Ternary Operators
You can technically write:
let result = score >= 90
? "A"
: score >= 80
? "B"
: "C";
Although valid, this can reduce readability.
For several conditions, an if...else if...else structure is often clearer.
The switch Statement
JavaScript also provides the switch statement for comparing one expression against multiple possible values.
Basic syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// fallback code
}
Example:
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week.");
break;
case "Friday":
console.log("Almost the weekend.");
break;
case "Saturday":
console.log("Weekend.");
break;
default:
console.log("Another day.");
}
The break statement stops execution from continuing into the next case.
Why break Matters in switch
Consider:
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("Apple");
case "banana":
console.log("Banana");
}
Without break, JavaScript can continue into subsequent cases after finding a match. This behavior is called fall-through.
Usually, you want:
switch (fruit) {
case "apple":
console.log("Apple");
break;
case "banana":
console.log("Banana");
break;
default:
console.log("Unknown fruit.");
}
Fall-through can be intentional when multiple cases should share the same result.
For example:
let day = "Saturday";
switch (day) {
case "Saturday":
case "Sunday":
console.log("Weekend");
break;
default:
console.log("Weekday");
}
Here, both weekend cases intentionally share the same code.
The default Case
The default case runs when none of the other cases matches.
switch (role) {
case "admin":
console.log("Full access");
break;
case "user":
console.log("Standard access");
break;
default:
console.log("Unknown role");
}
A default case is useful as a fallback.
switch Uses Strict Matching
A switch statement compares cases using strict comparison semantics.
For example:
let value = 5;
switch (value) {
case "5":
console.log("String five");
break;
case 5:
console.log("Number five");
break;
}
The second case matches because the value is the number 5, not the string "5".
Conditional Expressions
Conditions can be simple:
age >= 18
Or complex:
age >= 18 && hasID && !isBlocked
They can also include function calls:
if (isUserAllowed()) {
console.log("Allowed");
}
The important idea is that the resulting value is evaluated according to JavaScript’s truthiness rules.
Short-Circuit Evaluation
Logical operators can be used to conditionally execute expressions.
With &&:
isLoggedIn && showDashboard();
If isLoggedIn is falsy, showDashboard() is not evaluated.
With ||:
username || console.log("No username provided.");
If username is falsy, the second expression is evaluated.
This technique is useful, but for complex business logic, a normal if statement can be easier to understand.
Nullish Coalescing and Conditions
The nullish coalescing operator ?? is useful when you want to use a fallback only when a value is null or undefined.
let username = null;
let displayName = username ?? "Guest";
console.log(displayName);
The result is:
Guest
This differs from ||.
For example:
let count = 0;
let result = count || 10;
console.log(result);
The result is:
10
But:
let result = count ?? 10;
console.log(result);
produces:
0
This distinction is important when 0, false, or an empty string are valid values.
Optional Chaining in Conditions
Optional chaining ?. can safely access properties that may not exist.
let user = {};
if (user.profile?.name) {
console.log(user.profile.name);
}
If profile is missing, JavaScript does not throw an error for that access. The expression evaluates to undefined, which is falsy.
Combining Conditions
Multiple conditions can be combined:
let age = 30;
let country = "India";
let verified = true;
if (age >= 18 && country === "India" && verified) {
console.log("Conditions satisfied.");
}
Parentheses can make complex conditions easier to understand:
if ((age >= 18 && verified) || isAdmin) {
console.log("Access granted.");
}
Although JavaScript follows operator precedence rules, parentheses often make the intended logic clearer.
The Importance of Operator Precedence
Consider:
if (a || b && c) {
// ...
}
The && operation is evaluated before ||.
For readability, you may prefer:
if (a || (b && c)) {
// ...
}
Use parentheses when the logic could be misunderstood.
Comparing Strings
Conditions can compare strings:
let language = "JavaScript";
if (language === "JavaScript") {
console.log("Welcome to JavaScript.");
}
String comparisons are case-sensitive.
Therefore:
"JavaScript" === "javascript"
is:
false
If a case-insensitive comparison is required, you can normalize the values:
let language = "JAVASCRIPT";
if (language.toLowerCase() === "javascript") {
console.log("Matched.");
}
Comparing Numbers
Number comparisons are straightforward:
let price = 500;
if (price > 100) {
console.log("The product costs more than 100.");
}
Be careful when values come from HTML forms because form values are commonly strings.
For example:
let age = "20";
console.log(age === 20);
This is:
false
You can explicitly convert the value:
let age = Number("20");
if (age >= 18) {
console.log("Eligible.");
}
Explicit conversion can make your code’s intention clearer.
Conditions with Functions
Functions can return Boolean values and be used directly in conditionals.
function isAdult(age) {
return age >= 18;
}
if (isAdult(25)) {
console.log("Adult");
}
This approach can make complicated conditions easier to reuse.
Another example:
function hasPermission(user) {
return user.role === "admin";
}
if (hasPermission(currentUser)) {
console.log("Access granted.");
}
Conditions with Arrays
You can use array methods inside conditionals.
For example:
let numbers = [10, 20, 30];
if (numbers.includes(20)) {
console.log("The number exists.");
}
The includes() method returns a Boolean.
You can also use methods such as some():
let numbers = [2, 4, 7, 8];
if (numbers.some(number => number % 2 !== 0)) {
console.log("At least one odd number exists.");
}
Conditions with Objects
Object properties can also be checked:
let user = {
name: "Alex",
isAdmin: true
};
if (user.isAdmin) {
console.log("Administrator");
}
For checking whether an object has a property, use an appropriate property-checking method rather than relying only on truthiness when false, 0, or undefined could be valid values.
For example:
if (Object.hasOwn(user, "name")) {
console.log("The name property exists.");
}
Conditions and NaN
NaN means “Not-a-Number.”
It is falsy:
if (NaN) {
console.log("Runs");
}
The message does not run.
However, checking for NaN is better done with Number.isNaN():
let value = Number("hello");
if (Number.isNaN(value)) {
console.log("The value is not a valid number.");
}
Conditions and null
null represents an intentional absence of a value.
let user = null;
if (user === null) {
console.log("No user is available.");
}
Explicit comparison is often preferable when you specifically need to distinguish null.
Conditions and undefined
You may encounter undefined when a variable has not been assigned a value or when an object property does not exist.
let username;
if (username === undefined) {
console.log("Username is undefined.");
}
When appropriate, you can also use:
if (username === undefined) {
// ...
}
or use a broader existence/fallback pattern depending on the application’s requirements.
The else Block Is Optional
An if statement does not require an else.
if (isOnline) {
console.log("User is online.");
}
If the condition is false, nothing happens.
You should not add an else block unless there is a meaningful alternative action.
The else if Block Is Optional
You can have one or more else if branches:
if (condition1) {
// ...
} else if (condition2) {
// ...
}
You can also finish with else:
if (condition1) {
// ...
} else if (condition2) {
// ...
} else {
// ...
}
Multiple Independent if Statements
Do not confuse multiple independent if statements with an if...else if chain.
Example:
if (age >= 18) {
console.log("Adult");
}
if (hasLicense) {
console.log("Has license");
}
Both conditions can run.
With else if:
if (age >= 18) {
console.log("Adult");
} else if (hasLicense) {
console.log("Has license");
}
Only one branch of the chain runs.
Choose the structure based on whether the conditions are independent or mutually exclusive.
Early Returns
In functions, early returns can make conditional logic cleaner.
Instead of:
function processUser(user) {
if (user) {
if (user.isActive) {
console.log("Processing user.");
}
}
}
You can write:
function processUser(user) {
if (!user) {
return;
}
if (!user.isActive) {
return;
}
console.log("Processing user.");
}
This reduces nesting and often makes the main logic easier to follow.
Guard Clauses
An early-return pattern is often called a guard clause.
function withdraw(balance, amount) {
if (amount <= 0) {
return "Invalid amount";
}
if (amount > balance) {
return "Insufficient balance";
}
return "Withdrawal successful";
}
Guard clauses are especially useful when a function has several conditions that can prevent the main operation from continuing.
Common Mistakes with JavaScript Conditionals
Using = Instead of ===
A common mistake is:
if (age = 18) {
// ...
}
The = operator assigns a value. It does not compare values.
Usually, you want:
if (age === 18) {
// ...
}
Using == When Strict Equality Is Better
Although == is valid, implicit type conversion can create unexpected results.
Prefer:
if (value === expectedValue) {
// ...
}
when you want both type and value to match.
Forgetting Braces
This code can be misleading:
if (loggedIn)
console.log("Welcome");
console.log("Dashboard");
Only the first statement belongs to the if.
A clearer version is:
if (loggedIn) {
console.log("Welcome");
console.log("Dashboard");
}
Creating Very Long Conditions
This can become difficult to read:
if (age >= 18 && verified && active && country === "India" && !blocked && hasSubscription) {
// ...
}
Consider extracting meaningful parts into variables or functions:
let canAccess =
age >= 18 &&
verified &&
active &&
country === "India" &&
!blocked &&
hasSubscription;
if (canAccess) {
console.log("Access granted.");
}
Excessive Nesting
Deeply nested conditionals are harder to maintain.
Instead of repeatedly nesting blocks, consider guard clauses, helper functions, or combined conditions.
Forgetting break in switch
Without break, execution may continue into the next case.
Using a Ternary for Complex Logic
A ternary is excellent for simple choices:
let status = isOnline ? "Online" : "Offline";
It is less suitable when many conditions and statements are involved.
if Versus switch
Both can be used for decision-making, but they have different strengths.
Use if...else when conditions involve:
- Ranges
- Comparisons
- Multiple variables
- Complex Boolean expressions
- Different types of conditions
Example:
if (age >= 18 && hasID) {
console.log("Allowed");
}
Use switch when one expression is being compared against several known values:
switch (status) {
case "pending":
console.log("Waiting");
break;
case "approved":
console.log("Approved");
break;
case "rejected":
console.log("Rejected");
break;
}
The choice should be based on clarity rather than simply the number of cases.
Conditional Assignment
Sometimes a value depends on a condition.
Using if...else:
let message;
if (isLoggedIn) {
message = "Welcome";
} else {
message = "Please log in";
}
Using a ternary:
let message = isLoggedIn ? "Welcome" : "Please log in";
For a simple value selection, the ternary version is often convenient.
Conditions in Loops
Conditionals are frequently combined with loops.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i);
}
}
This prints the even numbers from 1 to 10.
Conditions can also be used with while loops:
let count = 0;
while (count < 5) {
if (count === 3) {
console.log("Reached three");
}
count++;
}
Conditions in Event Handling
JavaScript conditions are common in interactive web pages.
button.addEventListener("click", () => {
if (isLoggedIn) {
openDashboard();
} else {
showLogin();
}
});
The interface changes according to the user’s state.
Conditions in Form Validation
Form validation is another common use.
let email = "user@example.com";
if (email.includes("@")) {
console.log("Email looks valid.");
} else {
console.log("Please enter a valid email.");
}
Real applications should use more complete validation rules, but the example demonstrates the basic idea.
Conditions and User Permissions
Conditional logic can control access:
if (user.role === "admin") {
showAdminPanel();
} else {
showUserPanel();
}
Client-side conditions can control what a user sees, but they should not be treated as a security boundary. Sensitive authorization must also be enforced on the server.
Conditions and API Responses
Conditions are often used after receiving data from an API.
if (response.ok) {
console.log("Request successful.");
} else {
console.log("Request failed.");
}
You can also check specific application states:
if (data.status === "success") {
displayResults(data);
} else {
showError(data.message);
}
Conditions and Error Handling
Conditional checks can help prevent invalid operations:
if (!user) {
console.log("User not found.");
return;
}
console.log(user.name);
For exceptions, JavaScript also provides try...catch, which serves a different purpose from ordinary conditionals.
For example:
try {
const data = JSON.parse(input);
console.log(data);
} catch (error) {
console.log("Invalid JSON.");
}
A condition checks a known logical state. Exception handling deals with errors that occur during execution.
Best Practices for JavaScript Conditionals
Write conditions that clearly communicate their purpose.
Prefer strict equality when appropriate:
if (status === "active") {
// ...
}
Use meaningful variable names:
if (hasPermission) {
// ...
}
is easier to understand than:
if (x) {
// ...
}
Keep conditions reasonably short.
Use parentheses when they improve clarity.
Avoid unnecessary nesting.
Use early returns when they simplify functions.
Use switch when it makes multiple fixed-value cases easier to read.
Use ternary expressions for simple conditional values.
Do not rely on truthiness when the distinction between values such as 0, false, "", null, and undefined matters.
Use helper functions for complicated business rules.
A Practical Example
Consider a simple shopping discount system:
let total = 1500;
let isMember = true;
if (total >= 2000 && isMember) {
console.log("You receive a 20% discount.");
} else if (total >= 1000 && isMember) {
console.log("You receive a 10% discount.");
} else if (total >= 2000) {
console.log("You receive a 5% discount.");
} else {
console.log("No discount available.");
}
This example demonstrates how several conditions can be combined to represent business rules.
For a larger application, the discount calculation could be moved into a separate function so that it can be tested and reused.
A Simple Decision-Making Example
Here is another practical example:
function checkAccess(age, hasTicket, isBlocked) {
if (isBlocked) {
return "Access denied.";
}
if (age < 18) {
return "You must be 18 or older.";
}
if (!hasTicket) {
return "A valid ticket is required.";
}
return "Access granted.";
}
console.log(checkAccess(25, true, false));
This approach demonstrates a clean conditional structure using guard clauses.
JavaScript Conditional Syntax Summary
The main conditional tools can be summarized as follows:
// if
if (condition) {
// code
}
// if...else
if (condition) {
// code
} else {
// code
}
// if...else if...else
if (condition1) {
// code
} else if (condition2) {
// code
} else {
// code
}
// ternary
condition ? valueIfTrue : valueIfFalse;
// switch
switch (value) {
case option1:
// code
break;
case option2:
// code
break;
default:
// fallback
}
Final Thoughts
JavaScript conditionals give programs the ability to make decisions. The basic if statement is simple, but conditional logic becomes extremely powerful when combined with comparison operators, logical operators, functions, loops, objects, arrays, and other JavaScript features.
For simple decisions, use if. When there are two alternatives, if...else is usually appropriate. For several related conditions, else if can be useful. The ternary operator works well for short conditional expressions, while switch can make multiple fixed-value choices easier to organize.
Good conditional code is not only about making the program work. It should also be easy to read, test, debug, and maintain. Clear conditions, meaningful names, sensible ordering, appropriate use of strict equality, and limited nesting can make JavaScript code much more reliable.
Once you understand conditionals, you have one of the fundamental building blocks needed to create interactive websites, web applications, games, APIs, and other JavaScript-powered software.