JavaScript : Comparison and Logical Operators

Comparison and logical operators are fundamental in JavaScript for comparing values and making decisions based on those comparisons. They are used in conditional statements, loops, and boolean logic operations. Let's explore the common comparison and logical operators in JavaScript:

1. Comparison Operators:


Comparison operators compare two values and return a boolean result ( true or false ).

  • ==: Equal to (loose equality, does type coercion).
  • ===: Equal value and equal type (strict equality, no type coercion).
  • !=: Not equal to (loose inequality, does type coercion).
  • !==: Not equal value or not equal type (strict inequality, no type coercion).
  • >: Greater than.
  • <: Less than.
  • >=: Greater than or equal to.
  • <=: Less than or equal to.

Example:

let x = 5;
let y = 10;

console.log(x == y);  // Output: false
console.log(x !== y);  // Output: true
console.log(x > y);  // Output: false

 

2. Logical Operators:


Logical operators perform boolean logic operations on values and return a boolean result.

  • &&: Logical AND. Returns true if both operands are true.
  • ||: Logical OR. Returns true if at least one of the operands is true.
  • !: Logical NOT. Returns the opposite boolean value of the operand.

Example:

let isSunny = true;
let isWarm = false;

console.log(isSunny && isWarm);  // Output: false
console.log(isSunny || isWarm);  // Output: true
console.log(!isSunny);  // Output: false

 

3. Ternary Operator (Conditional Operator):


The ternary operator condition ? expr1 : expr2 evaluates condition. If condition is true , expr1 is returned; otherwise, expr2 is returned.

Example:

let age = 20;
let status = (age >= 18) ? 'Adult' : 'Minor';
console.log(status);  // Output: "Adult"

 

4. Nullish Coalescing Operator (??):


The nullish coalescing operator ?? returns the right-hand operand when the left-hand operand is null or undefined, otherwise, it returns the left-hand operand.

Example:

let name = null;
let defaultName = 'Guest';
let result = name ?? defaultName;
console.log(result);  // Output: "Guest"

 

These operators are essential for controlling the flow of your JavaScript code, making decisions, and performing boolean logic operations based on conditions.