CodeBlanks Logo Icon CodeBlanks

Difference between == and ===

JavaScript course · Beginner · Lesson 96/133

Learn equality operators that do and do not perform type conversion.

Difference between == and ===

JavaScript has two equality operators. == is loose equality: it converts the types before comparing. === is strict equality: it does not convert types.

For example 5 == "5" first turns the string "5" into a number and returns true. But 5 === "5" sees the types differ (number and string) and returns false. To avoid surprises, === is preferred most of the time.

Objects and reference comparison

Objects, arrays and functions are compared by reference. Even when two objects have the same content, different memory locations mean different objects.

Example: {} === {} returns false because two separate empty objects are created. But when you write const a = {}; and const b = a;, then a === b is true because both refer to the same object. The same rule applies to arrays.

Exercise Show two comparisons side by side

Define a function called checkStrict. It should take a and b parameters. In the body write the lines console.log(a === b) and console.log(a == b); this way you can compare the strict and loose results.

Show example solution
function checkStrict(a, b) {
  console.log(a === b);
  console.log(a == b);
}

Exercise Call with three pairs

The checkStrict function below is defined. Now call it with three pairs: checkStrict(5, "5"), checkStrict(null, undefined) and checkStrict(0, false). Put each call on its own line.

Show example solution
function checkStrict(a, b) {
  console.log(a === b);
  console.log(a == b);
}

checkStrict(5, "5");
checkStrict(null, undefined);
checkStrict(0, false);

Test yourself

  1. Which returns true with ===?

    • 5 === "5"
    • 5 === 5
    • null === undefined
    • 0 === false
    Show answer

    5 === 5 — Correct. 5 === 5 returns true because the type and value are the same.

  2. Write strict equality

    console.log(0 ____ "");
    Show answer
    console.log(0 === "");
  3. Match the operator to its property

    ==
    Converts types
    ===
    Keeps types
    !==
    Strict not-equal
    !=
    Not-equal

All lessons in Beginner