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:
Comparison operators compare two values and return a boolean result ( true or false ).
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
Logical operators perform boolean logic operations on values and return a boolean result.
Example:
let isSunny = true;
let isWarm = false;
console.log(isSunny && isWarm); // Output: false
console.log(isSunny || isWarm); // Output: true
console.log(!isSunny); // Output: false
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"
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.