JavaScript Logical Operators
JavaScript logical operators are essential tools used to make decisions, evaluate conditions, and control the flow of a program. They allow developers to combine multiple conditions, check whether a condition is true or false, and execute different operations based on the results.
Logical operators are commonly used in conditional statements such as if, else if, and while loops. They are also useful in form validation, user authentication, access control, search filters, and many other JavaScript applications.
JavaScript provides three main logical operators:
- Logical AND (
&&) - Logical OR (
||) - Logical NOT (
!)
Understanding these operators is important for anyone learning JavaScript because they help create efficient, flexible, and intelligent programs.
What Are JavaScript Logical Operators?
JavaScript logical operators are symbols that perform logical operations on expressions or values. They evaluate conditions and determine which result should be returned.
For example, imagine creating a website where users can access a dashboard only when they have entered the correct username and password. You need to check two conditions:
- The username must be correct.
- The password must be correct.
Both conditions must be true before the user can log in. This is a perfect example of using the logical AND (&&) operator.
Similarly, if a website allows users to log in using either an email address or a phone number, the logical OR (||) operator can be used.
Types of JavaScript Logical Operators
JavaScript has three primary logical operators. Each operator performs a different logical operation.
| Operator | Name | Description | ||
|---|---|---|---|---|
&& | Logical AND | Returns the right operand if the left operand is truthy; otherwise, returns the left operand. | ||
| ` | ` | Logical OR | Returns the left operand if it is truthy; otherwise, returns the right operand. | |
! | Logical NOT | Reverses the truthiness of a value and returns a Boolean. |
Let’s understand each logical operator with examples.
1. JavaScript Logical AND (&&) Operator
The logical AND operator (&&) checks whether two or more conditions are true.
It returns the right-hand operand when the left-hand operand is truthy. Otherwise, it returns the left-hand operand.
When used with Boolean values, the AND operator returns true only when all conditions are true.
Syntax:
condition1 && condition2;Example:
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive.");
} else {
console.log("You cannot drive.");
}Output:
You can drive.Explanation:
In this example, two conditions are checked:
age >= 18returnstrue.hasLicenseistrue.
Since both conditions are true, the logical AND operator evaluates to true, and the program displays the message “You can drive.”
Logical AND Truth Table
The following truth table explains how the AND operator works:
| Condition A | Condition B | Result |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
The AND operator returns true only when both operands are true.
Example: Checking Multiple Conditions
let username = "admin";
let password = "12345";
let isActive = true;
if (username === "admin" && password === "12345" && isActive) {
console.log("Login successful!");
} else {
console.log("Invalid login details.");
}Output:
Login successful!In this example, all three conditions must be true to display the successful login message.
2. JavaScript Logical OR (||) Operator
The logical OR operator (||) checks whether at least one of the given conditions is true.
It returns the left-hand operand if it is truthy. Otherwise, it returns the right-hand operand.
When used with Boolean values, the OR operator returns true if at least one condition is true. It returns false only when all conditions are false.
Syntax:
condition1 || condition2;Example:
let isWeekend = false;
let isHoliday = true;
if (isWeekend || isHoliday) {
console.log("You can relax today.");
} else {
console.log("You have to work today.");
}Output:
You can relax today.Explanation:
In this example:
isWeekendisfalse.isHolidayistrue.
Because at least one condition is true, the OR operator evaluates the expression as true.
Logical OR Truth Table
| Condition A | Condition B | Result |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
The OR operator returns false only when both operands are false.
Example: Checking User Access
let isAdmin = false;
let isEditor = true;
if (isAdmin || isEditor) {
console.log("You have permission to edit content.");
} else {
console.log("Access denied.");
}Output:
You have permission to edit content.In this example, a user can edit content if they are either an administrator or an editor.
3. JavaScript Logical NOT (!) Operator
The logical NOT operator (!) reverses the Boolean interpretation of a value.
If a value is truthy, the NOT operator returns false. If a value is falsy, it returns true.
Unlike AND and OR, the NOT operator works with a single operand.
Syntax:
!condition;Example:
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in first.");
} else {
console.log("Welcome back!");
}Output:
Please log in first.Explanation:
The variable isLoggedIn contains the Boolean value false.
The NOT operator reverses it:
!falseThe result is:
trueTherefore, the program executes the first block and displays “Please log in first.”
Logical NOT Truth Table
| Condition | Result |
|---|---|
| true | false |
| false | true |
Example: Checking Whether a User Is Not an Administrator
let isAdmin = false;
if (!isAdmin) {
console.log("You are not an administrator.");
}Output:
You are not an administrator.The NOT operator is useful when you want to check whether something is not true.
Understanding Truthy and Falsy Values in JavaScript
To understand logical operators properly, you should know about truthy and falsy values.
JavaScript does not always require a condition to contain an actual Boolean value. It can evaluate other data types as either truthy or falsy.
Truthy Values
Truthy values are values that JavaScript treats as true when evaluated in a Boolean context.
Examples include:
if ("Hello") {
console.log("This is truthy.");
}
if (100) {
console.log("This is also truthy.");
}
if ([]) {
console.log("An empty array is truthy.");
}
if ({}) {
console.log("An empty object is truthy.");
}Output:
This is truthy.
This is also truthy.
An empty array is truthy.
An empty object is truthy.Common truthy values include:
- Non-empty strings, such as
"JavaScript". - Non-zero numbers, such as
10and-5. - Empty arrays (
[]). - Empty objects (
{}). - Functions.
- The Boolean value
true.
Falsy Values
Falsy values are values that JavaScript treats as false when evaluated in a Boolean context.
JavaScript has the following commonly encountered falsy values:
| Value | Description |
|---|---|
false | Boolean false |
0 | Zero |
-0 | Negative zero |
0n | BigInt zero |
"" | Empty string |
null | Absence of a value |
undefined | An undefined value |
NaN | Not a Number |
Example:
let name = "";
if (name) {
console.log("Name is available.");
} else {
console.log("Name is empty.");
}Output:
Name is empty.Because an empty string is falsy, JavaScript executes the else block.
Short-Circuit Evaluation in JavaScript
Short-circuit evaluation is an important feature of JavaScript logical operators.
It means JavaScript evaluates logical expressions from left to right and may stop evaluating as soon as the result is determined.
Both AND (&&) and OR (||) operators support short-circuit evaluation.
Short-Circuit Evaluation with AND (&&)
The AND operator stops evaluating when it encounters a falsy value.
Example:
let age = 15;
age >= 18 && console.log("You are an adult.");Output:
There is no output because age >= 18 evaluates to false. JavaScript does not execute the expression on the right side.
Short-Circuit Evaluation with OR (||)
The OR operator stops evaluating when it encounters a truthy value.
Example:
let name = "John";
let result = name || "Guest";
console.log(result);Output:
JohnSince name contains a truthy value, JavaScript does not need to evaluate the second operand.
Short-circuit evaluation can help improve code readability and avoid unnecessary operations.
Difference Between Logical AND, OR, and NOT Operators
Although all three operators are used for logical operations, they work differently.
| Feature | AND (&&) | OR (||) | NOT (!) |
|—|—|—|—|
| Purpose | Checks all conditions | Checks at least one condition | Reverses truthiness |
| Operands | Two or more | Two or more | One |
| Returns true when | All conditions are true | At least one condition is true | Original value is falsy |
| Returns false when | At least one condition is false | All conditions are false | Original value is truthy |
| Short-circuiting | Yes | Yes | Not applicable |
JavaScript Logical Operators with Conditional Statements
Logical operators are frequently used with conditional statements to make decisions based on multiple conditions.
Example 1: Using AND with an If Statement
let age = 22;
let country = "India";
if (age >= 18 && country === "India") {
console.log("You meet both conditions.");
} else {
console.log("You do not meet the requirements.");
}Output:
You meet both conditions.Example 2: Using OR with an If Statement
let temperature = 38;
if (temperature > 35 || temperature < 10) {
console.log("Extreme temperature.");
} else {
console.log("Normal temperature.");
}Output:
Extreme temperature.Example 3: Using NOT with an If-Else Statement
let isAvailable = false;
if (!isAvailable) {
console.log("The product is currently unavailable.");
} else {
console.log("The product is available.");
}Output:
The product is currently unavailable.Combining Multiple Logical Operators
JavaScript allows developers to combine multiple logical operators in a single expression.
You can use AND, OR, and NOT together to evaluate complex conditions.
Example:
let age = 25;
let hasID = true;
let isBanned = false;
if (age >= 18 && hasID && !isBanned) {
console.log("Access granted.");
} else {
console.log("Access denied.");
}Output:
Access granted.Explanation:
The program checks three conditions:
- The user must be at least 18 years old.
- The user must have valid identification.
- The user must not be banned.
All conditions are satisfied, so the program displays “Access granted.”
Operator Precedence in JavaScript Logical Operators
When multiple logical operators are used in the same expression, JavaScript follows operator precedence rules to determine the order of evaluation.
The precedence of the three logical operators is:
- Logical NOT (
!) has the highest precedence. - Logical AND (
&&) has the next highest precedence. - Logical OR (
||) has the lowest precedence.
Example:
let a = true;
let b = false;
let c = true;
let result = a || b && c;
console.log(result);Output:
trueExplanation:
The AND operator is evaluated before the OR operator.
The expression becomes:
true || (false && true)First:
false && trueResult:
falseThen:
true || falseFinal result:
trueUsing Parentheses to Control Evaluation
Parentheses can make logical expressions easier to understand and control the order of evaluation.
Example:
let a = true;
let b = false;
let c = true;
let result = (a || b) && c;
console.log(result);Output:
trueUsing parentheses is recommended when working with complex logical expressions because it improves readability and reduces mistakes.
Difference Between Logical Operators and Comparison Operators
Logical operators and comparison operators are both used in JavaScript conditions, but they have different purposes.
Comparison operators compare two values and return a Boolean result.
Examples of comparison operators include:
==– Equal to.===– Strictly equal to.!=– Not equal to.!==– Strictly not equal to.>– Greater than.<– Less than.>=– Greater than or equal to.<=– Less than or equal to.
Logical operators combine or reverse the results of expressions.
Example:
let age = 20;
let marks = 75;
let result = age >= 18 && marks >= 50;
console.log(result);Output:
trueHere, the comparison operators check the age and marks, while the logical AND operator combines both results.
Practical Uses of JavaScript Logical Operators
Logical operators are used in many real-world JavaScript applications. They help developers create flexible conditions and manage program behavior.
1. User Login Validation
Logical operators can check whether a user has entered the required login information.
let username = "admin";
let password = "admin123";
if (username === "admin" && password === "admin123") {
console.log("Login successful.");
} else {
console.log("Incorrect username or password.");
}2. Form Validation
They can check whether users have completed all required fields in a form.
let name = "Rahul";
let email = "rahul@example.com";
let password = "12345678";
if (name && email && password.length >= 8) {
console.log("Form submitted successfully.");
} else {
console.log("Please complete all required fields.");
}3. Checking User Permissions
Logical operators help determine whether a user has permission to perform a particular action.
let isAdmin = false;
let isEditor = true;
if (isAdmin || isEditor) {
console.log("You can publish articles.");
} else {
console.log("You do not have publishing permission.");
}4. Checking Product Availability
An online shopping website can use logical operators to check product availability.
let stock = 10;
let isAvailable = true;
if (stock > 0 && isAvailable) {
console.log("Product is available.");
} else {
console.log("Product is out of stock.");
}5. Checking Age Restrictions
Logical operators can check whether a user meets specific age requirements.
let age = 21;
if (age >= 18 && age <= 60) {
console.log("You meet the age requirements.");
} else {
console.log("You do not meet the age requirements.");
}Common Mistakes When Using JavaScript Logical Operators
Beginners sometimes make mistakes when working with logical operators. Understanding these common issues can help you write better JavaScript code.
1. Using a Single Ampersand Instead of Double Ampersands
The logical AND operator uses two ampersands (&&), not one (&).
Incorrect:
let result = true & false;Correct:
let result = true && false;The single ampersand is a bitwise AND operator, which performs a different operation.
2. Confusing Logical OR with Logical AND
The AND operator requires all conditions to be true, whereas the OR operator requires only one condition to be true.
Incorrect for an either-condition requirement:
let age = 20;
let hasPermission = false;
if (age >= 18 && hasPermission) {
console.log("Access granted.");
}If the requirement is to allow access when either condition is satisfied, use OR:
if (age >= 18 || hasPermission) {
console.log("Access granted.");
}3. Forgetting Operator Precedence
JavaScript evaluates NOT before AND and AND before OR.
When conditions become complex, use parentheses to make your intentions clear.
let result = (true || false) && true;
console.log(result);4. Not Understanding Truthy and Falsy Values
Remember that values such as 0, "", null, and undefined are falsy, while empty arrays and empty objects are truthy.
let value = [];
if (value) {
console.log("The condition is true.");
}Output:
The condition is true.An empty array is truthy in JavaScript.
5. Assuming Logical Operators Always Return Boolean Values
One of the most important things to understand is that && and || do not always return true or false. They return one of their actual operands.
let name = "";
console.log(name || "Guest");Output:
GuestHowever, the NOT operator always returns a Boolean value.
Best Practices for Using JavaScript Logical Operators
Follow these practices to make your JavaScript code easier to read, understand, and maintain.
- Use
&&when every condition must be satisfied. - Use
||when at least one condition must be satisfied. - Use
!when you need to reverse the truthiness of a value. - Use parentheses when combining multiple logical operators.
- Avoid unnecessarily complicated conditional expressions.
- Understand truthy and falsy values before using logical operators.
- Use strict equality (
===) when comparing values whenever appropriate. - Use meaningful variable names to make conditions easier to understand.
- Remember that
&&and||return operands rather than always returning Boolean values. - Use
??when you specifically want to provide a fallback only fornullorundefined.
JavaScript Logical Operators vs Nullish Coalescing Operator
JavaScript also provides the nullish coalescing operator (??), which is useful when working with missing values.
Although ?? is not one of the three primary logical operators, it is closely related to logical OR.
The logical OR operator returns the right-hand value when the left-hand value is falsy.
The nullish coalescing operator returns the right-hand value only when the left-hand value is null or undefined.
Example using OR (||):
let username = "";
let result = username || "Guest";
console.log(result);Output:
GuestExample using Nullish Coalescing (??):
let username = "";
let result = username ?? "Guest";
console.log(result);Output:
The second example displays an empty string because an empty string is not nullish.
This distinction is important when handling user input, configuration values, and default settings.
Conclusion
JavaScript logical operators are fundamental programming tools that help developers evaluate conditions and control program execution. The three main logical operators are AND (&&), OR (||), and NOT (!).
The AND operator checks whether all conditions are true, the OR operator checks whether at least one condition is true, and the NOT operator reverses the truthiness of a value.
These operators are widely used in conditional statements, form validation, authentication, user permissions, shopping websites, and many other applications.
By understanding how logical operators work, including truthy and falsy values, short-circuit evaluation, and operator precedence, you can write cleaner and more effective JavaScript programs.
If you are learning JavaScript, practise these operators with different examples and gradually combine multiple conditions to improve your programming skills.
Frequently Asked Questions (FAQs)
1. What are logical operators in JavaScript?
Logical operators in JavaScript are symbols used to combine conditions, evaluate expressions, and make decisions in a program. The three main logical operators are AND (&&), OR (||), and NOT (!).
2. How many logical operators are there in JavaScript?
JavaScript has three primary logical operators: AND (&&), OR (||), and NOT (!). These operators are used to evaluate logical expressions and control program execution.
3. What is the AND (&&) operator in JavaScript?
The AND operator checks whether all conditions are true. It returns true when every operand is truthy and returns the first falsy operand when one is encountered.
4. What is the OR (||) operator in JavaScript?
The OR operator checks whether at least one condition is true. It returns the first truthy operand or the final operand if none is truthy.
5. What is the NOT (!) operator in JavaScript?
The NOT operator reverses the truthiness of a value. It converts truthy values to false and falsy values to true.
6. What is the difference between AND and OR operators?
The AND operator requires all conditions to be true, whereas the OR operator requires at least one condition to be true. AND uses &&, while OR uses ||.
7. What is short-circuit evaluation in JavaScript?
Short-circuit evaluation occurs when JavaScript stops evaluating a logical expression as soon as its result is determined. The AND operator stops at the first falsy operand, while the OR operator stops at the first truthy operand.
8. Do JavaScript logical operators always return Boolean values?
No. The AND (&&) and OR (||) operators can return the actual value of one of their operands. The NOT (!) operator always returns a Boolean value.
9. What is the difference between || and ?? in JavaScript?
The OR (||) operator uses the right-hand value when the left-hand value is falsy. The nullish coalescing (??) operator uses the right-hand value only when the left-hand value is null or undefined.
10. Where are JavaScript logical operators used?
JavaScript logical operators are commonly used in conditional statements, form validation, login systems, access permissions, search filters, shopping websites, and other applications that require multiple conditions to be evaluated.