CodeBlanks Logo Icon CodeBlanks

Comparison operators

Learn to compare values with ==, ===, !=, <, >, <= and >=.

Comparison operators

Comparison operators compare two values and return true or false: === (equal), !== (not equal), > (greater than), < (less than), >= (greater or equal), <= (less or equal).

For example, 5 > 3 returns true, 5 < 3 returns false. These operators are used in if conditions and loop conditions.

The result is a boolean; so it can also be assigned to a variable, like const canDrive = age >= 18.

=== vs ==

JavaScript has two equality operators: === (strict) and == (loose). === checks both value and type; == checks only value and does type coercion.

For example, 5 === '5' returns false (number and string are different types). But 5 == '5' returns true; because == converts the string to a number.

To avoid unexpected results, modern code always uses ===. Avoid ==.

Practice Comparison results

Declare a = 5 and b = '5'. Compare with console.log(a === b) and console.log(a == b). Also check console.log(a > 3).

Starter code

index.js
const a = 5;
const b = "5";
// Compare with ===, == and >
// Log all three with console.log

Sample solution

index.js
const a = 5;
const b = "5";
console.log(a === b);
console.log(a == b);
console.log(a > 3);

Expected output

false
true
true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the operators

Term Meaning
=== Strict equality
== Loose equality
!== Strict inequality
> Greater than

2 What is the difference between === and ==?

  • === checks both value and type, == only value Correct answer
  • === only value, == both value and type
  • They are the same
  • === is for numbers, == for strings

Explanation: === checks value and type; == only value.

3 Strict equality

Question
if (a ____ b) { console.log('equal'); }
Answer
if (a === b) { console.log('equal'); }

Explanation: === checks strict equality.

All lessons in Beginner