JavaScript enhances the power of the programming language with fundamental building blocks like comparison and logical operators. These operators are used in conditional statements, loops, and many other scenarios. Here’s a guide on how to use comparison and logical operators in JavaScript:
1. Comparison Operators
Comparison operators are used to compare two values and are commonly used in conditional statements. Here are the most commonly used comparison operators:
==
: Equality operator checks if two values are equal.!=
: Inequality operator checks if two values are not equal.===
: Strict equality operator checks if both the values and their data types are equal.!==
: Strict inequality operator checks if both the values and their data types are not equal.>
: Greater than operator checks if one value is greater than another.<
: Less than operator checks if one value is less than another.>=
: Greater than or equal to operator checks if one value is greater than or equal to another.<=
: Less than or equal to operator checks if one value is less than or equal to another.
Example:
let x = 5;
let y = 10;
console.log(x == y); // false
console.log(x != y); // true
console.log(x === "5"); // false
console.log(x !== "5"); // true
console.log(x > y); // false
console.log(x < y); // true
console.log(x >= y); // false
console.log(x <= y); // true
2. Logical Operators
Logical operators are used to combine or invert multiple conditions. There are three main logical operators in JavaScript:
&&
: And (AND) operator evaluates to true if both conditions are true.||
: Or (OR) operator evaluates to true if at least one of the conditions is true.!
: Not (NOT) operator inverts a condition, meaning if it’s true, it becomes false, and if it’s false, it becomes true.
Example:
let a = 5;
let b = 10;
let c = 15;
console.log(a < b && b < c); // true
console.log(a < b || b > c); // true
console.log(!(a < b)); // false
These examples provide simple yet explanatory code snippets to demonstrate how comparison and logical operators work in JavaScript.