Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Logical Operators in JavaScript

The Logical operators operate on a set of operands and return one of the operands as a return value. It is typically used on boolean operands, in which case the return value is a boolean. If the operands and not boolean values, then logical operators may return a non-boolean value. JavaScript has four logical operators. They are AND (&& ), OR ( || ) , NOT (!) & Nullish coalescing operator (??).

The syntax is as follows

boolean data type, truthy & falsy

The logical operators convert the operand to the boolean is a primitive type. The boolean represents a simple true/false value.

Every possible value in JavaScript can be converted to true & false. For Example, converting 100 to boolean will result in a true. And 0 becomes false.

Those values, which converts to false are known as falsy. And those, which converts to true are Truthy.

There are eight possible falsy values. They are

  1. false,
  2. 0 (zero),
  3. -0 (minus zero) ,
  4. 0n (BigInt zero) ,
  5. " " (empty string),
  6. null,
  7. undefined &
  8. NaN.

All other values convert to true, hence we call them truthy values.

OR (||)

Logical OR for a set of operands is true if and only if one of the operands convert to true (truthy). It returns the first truthy operand.

The Logical OR is denoted pipe symbol ||. The syntax is as shown below

expr1 || expr2

If expr1 can be converted to true, returns expr1; else, returns expr2.

  1. The operator evaluates the operands from left to right. i.e. It evaluates the expr1 first, and then expr2.
  2. It stops when it finds the first operand that evaluates to true and returns that operand. it does not evaluate the subsequent operands. This is known as a short circuit evaluation.
  3. If all operands evaluate to false, then it returns the last operand.

Example

In the following example a > 5 is the first expression and b > 5 is the second expression. Since a > 5 is true, it evaluates the expression a > 5 and returns true

                            
let a=10
let b=15
 
console.log(a > 5 || b > 5)  //true
console.log(a > 5 || b < 5)  //true although the b < 5 is false
 
                     
                            
                        

In the following example, both the operands are not booleans. Both "Hello" & 100 are truthy values. Hence OR returns whichever appears first.

                            
let strVar="Hello"
let numVar=100;
 
console.log(strVar || numVar)   //Hello
console.log(numVar || strVar)   //100
   
 
                     
                            
                        

option1, option2 & option3 are all undefined. A undefined is a falsy value. Hence the first OR statement returns "Default"

But, when we assign a value to option3, it becomes truthy. Hence the next OR statement returns Option3

                            
let option1, option2, option3
console.log(option1 || option2 || option3 || "Default")  //Default
 
 
option3="option3"
console.log(option1 || option2 || option3 || "Default")   //option3
 
                     
                            
                        

You can chain multiple operands in a single statement.

                            
let a=10
let b=15
 
console.log(a > 5 || b > 5 || b < a || a + b < 20 )  //true
 
//b
 
                     
                            
                        

The OR returns false only when both the operands are false. For all other combinations, it returns true.

                            
console.log(true  || false)  //true
console.log(false || true)   //true
console.log(true  || true)   //true
console.log(false || false)  //false
                     
                            
                        

AND (&&)

Logical AND for a set of operands is true if and only if all of its operands are true. It returns the first falsy operand. If all the operands are true, then it returns the last operand.

The Logical AND is denoted by symbol &&. The syntax is as shown below

  1. The operator evaluates the operands from left to right. i.e. It evaluates the expr1 first, and then expr2.
  2. It stops when it finds the first operand that evaluates to false and returns that operand. it does not evaluate the subsequent operands. This is known as a short circuit evaluation.
  3. If all operands evaluate to true, then it returns the last operand.

expr1 && expr2

If expr1 can be converted to true, returns expr2; else, returns expr1.

Example

In the first statement, both a >5 & b >5 are true. Hence it returns true. But the second AND statement b <5 is false, hence it returns false.>

                            
let a=10
let b=15
 
console.log(a > 5 && b > 5)  //true
console.log(a > 5 && b < 5)  //false  
//a > 5 is true, but b < 5 is false hence returns false 
 b  
 
                     
                            
                        

option1, option2 & option3 are all undefined. a undefined is a falsy value. Hence the first AND statement returns undefined.

But, when we assign a value to all options. now all of them become truthy. Hence the next AND statement returns Option3 (last truthy value).

                            
let option1, option2, option3
console.log(option1 && option2 && option3)  //undefined
 
 
option1="option1"
option2="option2"
option3="option3"
console.log(option1 && option2 && option3)  //option3
 
                     
                            
                        

AND returns true only if both operands are true. for all other combination returns false.

                            
console.log(true  && false)  //false
console.log(false && true)   //false
console.log(true  && true)   //true
console.log(false && false)  //false
 
 
                     
                            
                        

NOT (!)

The Logical NOT operator takes only one Operand and converts it to a boolean. Then it produces true, if the operand evaluates to false, and false, if the operand evaluates to true

Syntax

        
 !expr

 
        
    

The NOT operator always returns a boolean value.

Examples

        
alert( !true ); // false
alert( !0 ); // true

 
        
    

You can use the !! double not to convert a value into a boolean. The output of !! is the same as the Boolean global function

        
console.log(!"a")   //false
console.log(!!"a")  //true
 
console.log(Boolean("a")) //true
 
 
        
    

Notes on Logical Operators

The logical operators in JavaScruot work differently compared to the other programming languages like C, C++, or C#. The following are some of the important points to remember.

Operands can be of any type

The Operands of the Logical operators can be of any type. i.e because every possible value in JavaScript can be converted to true & false

Returns any value

As you can see from the above examples, the logical operators can return any value. In fact, they return one of the operands.

Evaluated from left to right

Expressions are evaluated from left to right.

Short-circuit evaluation

If a match is found, then the evaluation stops, and the operand is returned. For Example for an OR Operator, evaluation stops when it finds the first truthy operand. And for AND operator is it the first falsy operand.

        
console.log(true || alert("Hello"))
  //alert is never evaluated
 
console.log(false || alert("Hello"))
 
        
    

AND & OR together

You can mix AND & OR together, but remember the operator Precedence. The following is the list of operator Precedence of logical operators along with some other relevant operators.

  1. ( ) Parenthesis or Grouping
  2. ! Logical NOT
  3. == Equality
  4. != Not equal
  5. === Strict Equality
  6. !== Not strict Equal
  7. && logical AND
  8. || Logical OR
  9. ?? Nullish coalescing operator

Always use the parenthesis to group the operands together to increase readability and also override the operator precedence.

In the example, below && is evaluated first resulting in false and then || is evaluated. Hence it returns true

                
true || false && false  //true



By using the parentheses we can force the || to evaluate first and then the &&. Now the expression returns false.


(true || false) && false   //false