Skip to main content

JavaScript Comparison Operators (Live Playground)

Comparison operators are used to compare two values and return a boolean result, either true or false, based on the comparison. In this tutorial, we'll explore the most commonly used comparison operators in JavaScript and learn how to use them in our code.

Equal (==)

The equal operator checks if two values are equal and returns true if they are, or false if they are not.

Example:

const a = 10;
const b = '10';
console.log(a == b); // Output: true

Note that the equal operator performs type coercion, meaning it converts the operands to the same type before making the comparison.

Live Playground, Try it Yourself

Not equal (!=)

The not equal operator checks if two values are not equal and returns true if they are not, or false if they are.

Example:

const a = 10;
const b = 20;
console.log(a != b); // Output: true
Live Playground, Try it Yourself

Strictly equal (===)

The strictly equal operator checks if two values are equal in both value and type and returns true if they are, or false if they are not.

Example:

const a = 10;
const b = '10';
console.log(a === b); // Output: false
Live Playground, Try it Yourself

Strictly not equal (!==)

The strictly not equal operator checks if two values are not equal in either value or type and returns true if they are not, or false if they are.

Example:

const a = 10;
const b = '10';
console.log(a !== b); // Output: true
Live Playground, Try it Yourself

Greater than (>), Less than (<), Greater than or equal to (>=), and Less than or equal to (<=)

These operators are used to compare two values and determine their relative order.

Example:

const a = 10;
const b = 20;
console.log(a > b); // Output: false
console.log(a < b); // Output: true
console.log(a >= b); // Output: false
console.log(a <= b); // Output: true
Live Playground, Try it Yourself

Conclusion

Understanding and using comparison operators is essential for evaluating expressions and making decisions in your JavaScript programs. Familiarize yourself with the basic comparison operators, such as equal, not equal, strictly equal, strictly not equal, and the various relational operators, to create more complex conditions and control the flow of your code.