JavaScript Logical Operators with Examples

javascript logical operators

Logical operators in JavaScript let you check conditions and combine multiple checks in your code. In this guide, you will learn how logical operators work in JavaScript with examples.

Logical operators work with Boolean values and can also work on other types like numbers or strings.

You can use them to run code when specific conditions are true, or prevent code when conditions are false.

Here are the types of logical operators in JavaScript:

  • The AND (&&) operator
  • OR (||) operator
  • The NOT(!) operator
  • The XOR (Exclusive OR)
  • Equivalence (EQV)
  • Implication (IMP)

Let’s take each one in-depth.

The AND (&&) Operator

The AND operator checks if two conditions are true. It gives true only when both are true, otherwise it gives false.

let a = true;
let b = false;
console.log(a && b); // Output: false

A is true, but B is false. The output is false because AND needs both true. The output becomes true only when A and B are both true.

The OR (||) Operator

The OR operator checks if at least one condition is true. It returns true if either side is true and only returns false if both sides are false.

let a = true;
let b = false;
console.log(a || b); // Output: true

The a is true and B is false. OR gives true when at least one is true. It becomes false only if both are false.

The NOT (!) Operator

The NOT operator flips a Boolean value. True becomes false, and false becomes true. It helps when you need to reverse a condition.

let a = true;
console.log(!a); // Output: false

The a is true, but the ! operator turns it false. It acts as a logical “opposite” in conditions.

The XOR (Exclusive OR) Operator

XOR means Exclusive OR. It gives true only when one value is true, not both.

let a = true;
let b = false;
console.log(a ^ b); // Output: true

The a is true and b is false. XOR gives true since only one value is true. It becomes false if both are true or both are false.

Equivalence (EQV) Operator

Equivalence checks whether both values are the same. It gives true if both are true or both are false, and false.

let a = true;
let b = true;
console.log(!(a ^ b)); // Output: true

XOR of a and b is false because both are true. If you apply NOT (!) flips it to true, and it shows EQV behavior.

Implication (IMP) Operator

Implication shows “if… then…” logic. A → B is false only when A is true and B is false.

let a = true;
let b = false;
console.log(!a || b); // Output: false

A is true and B is false. Implication equals! A OR B. Here, !A is false and B is false, so the result is false.

Combine Multiple Logical Operators

You can join more than one logical operator in the same condition. A complex condition can check many cases in a single step. You must use brackets to group parts so the program checks them in the correct order.

Here is an example:

let age = 20;
let hasID = true;
let isVIP = false;

if ((age >= 18 && hasID) || isVIP) {
  console.log("Access granted");
} else {
  console.log("Access denied");
}

Output:

Access granted

The condition checks two possible cases for entry. The first case requires age to be 18 or more and the person to have ID. The second case allows entry if the person is VIP. Brackets make sure the age and ID check run together before the OR check.

Operator Precedence in Logical Expressions

Logical operators have an order that decides which part runs first. In JavaScript, ! runs before &&, and && runs before ||. You can use brackets to change this order when needed.

let result = !false && false || true;
console.log(result);

let resultWithBrackets = !(false && false) || true;
console.log(resultWithBrackets);

The output:

true
true

In the first check, !false runs first to give true. Then true && false gives false. Finally, false || true gives true. In the second check, brackets force false && false to run before the NOT.

The outcome remains true in this case, but brackets can change results in other cases.

Logical Operators with Non-Boolean Values

Logical operators in JavaScript can return values that are not true or false. They return the value of the operand that decides the result.

For example:

let name = "" || "Anonymouse user";
console.log(name);

let score = 0 && 100;
console.log(score);

The output:

Guest
0

In the first check, "" is falsy, so || returns "Guest". In the second check, 0 is falsy, so && stops early and returns 0. This shows how these operators can pass actual values instead of only true or false.

Truthy and Falsy Values in JavaScript

JavaScript treats some values as true and some as false in a Boolean check. Numbers except zero, non-empty strings, and objects are truthy. Zero, empty strings, null, undefined, and NaN are falsy.

if ("Hello") {
  console.log("This is truthy");
}

if (0) {
  console.log("This will not run");
}

The output:

This is truthy

The string "Hello" is truthy, so the first block runs. The number 0 is falsy, so the second block does not run. This rule applies to many types in JavaScript.

Use Logical Operators for Conditional Execution

You can run code only when a specific value is truthy or falsy. This avoids extra if statements. Logical operators can also return a value that you can use.

Here is an example:

let isLoggedIn = true;
isLoggedIn && console.log("Welcome back");

let user = null;
let displayName = user || "Guest";
console.log(displayName);

The output:

Welcome back
Guest

The first check runs the console.log only when isLoggedIn is true. The second check assigns "Guest" when user is null. Both cases use logical operators to replace full if statements.

Examples of JavaScript Logical Operators

Combine && and ||:

let age = 25;
let hasID = true;
let isMember = false;

if ((age >= 18 && hasID) || isMember) {
  console.log("Access granted");
}

The output:

Access granted

It checks if the person is 18 or older with an ID, or if the person is a member. Both options allow access.

Use || for Default Value:

let mainColor = null;
let backupColor = "Blue";
let activeColor = mainColor || backupColor;
console.log(activeColor);

There are two variables. It assigns each one to the other. It takes the backup if the main one is null. The || operator picks the first true value.

Here is the output:

Blue

Short-Circuit with &&:

let isLoggedIn = true;
let showWelcome = () => console.log("Welcome back");

isLoggedIn && showWelcome();

The output:

Welcome back

This runs the function “showWelcome” when “isLoggedIn” is true. The && operator stops when the first value is false.

Check Non-Boolean Values:

let value = "Hello" && 42;
console.log(value); // 42

This gives you 42 because both values are true, and && returns the last one when all are true.

Wrapping Up

You learned how the logical operators work and how JavaScript decides the order of checks with examples.

Here is a quick recap:

  • You can combine multiple operators in one statement.
  • You can change the order with brackets, use them for conditional code, and return values that are not just true or false.

FAQs

What are JavaScript logical operators and how to use them?

JavaScript logical operators allow you to combine or reverse conditions. Main operators:
  • && - Logical AND
  • || - Logical OR
  • ! - Logical NOT
Example:

let a = true;
let b = false;

console.log(a && b); // false
console.log(a || b); // true
console.log(!a);     // false

How does the AND (&&) operator work in JavaScript?

The && operator returns true if both conditions are true. Example:

let age = 25;
if (age > 18 && age < 30) {
  console.log("Age is between 18 and 30");
}

What is short-circuit evaluation in JavaScript logical operators?

Short-circuit evaluation stops checking conditions once the result is determined. Example with &&:

let x = 5;
x > 0 && console.log("Positive number");
// "Positive number" prints because first condition is true
Example with ||:

let name = "";
let user = name || "Guest";
console.log(user); // "Guest"

Similar Reads

JavaScript valueOf Function: How it Works with Examples

You will learn what the JavaScript valueOf function does and how it works. It returns the primitive value of an…

JavaScript Loops and Iteration: How They Work with Examples

You use loops in JavaScript to repeat code without copying it many times. This helps when you handle lots of…

JavaScript Math sqrt: How to Find Square Root of a Number

JavaScript Math.sqrt() solves the need to get square roots fast. Before it, you wrote custom code or used loops. It…

Understanding JavaScript Arithmetic Operators

JavaScript arithmetic operators let you add, subtract, multiply, or divide numbers. You can also use them to find remainders or…

JavaScript Math.max(): How to Find the Highest Number

Math.max() is a built-in JavaScript function that returns the highest number from a list of values. It has been part…

JavaScript Optional Chaining “?”: How it Works with Examples

JavaScript optional chaining lets you access object values without runtime errors. It checks if a property exists before access and…

JavaScript Polyfilling & Transpiling Guide for Beginners

JavaScript moves fast, and new features come. Some browsers do not support these features and cause issues for users. Developers…

Math.cbrt in JavaScript: How to Finds Cube Roots

JavaScript added Math.cbrt to solve cube roots. Before that, developers used custom code or Math.pow with 1/3. It works with…

How Does JavaScript Work to Run Code in the Web Browser

Click a button on a website. Something changes. A menu opens or a message pops up. That’s how JavaScript works.…

JavaScript Object Methods with Examples

JavaScript object methods are simple ways to handle data inside objects. An object can hold many values, and methods give…

Previous Article

PHP array_intersect_assoc: How it Works with Examples

Next Article

HTML Skip Link Guide for Beginners and Web Developers

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.