DeployU
Interviews / Frontend Engineering / What is the difference between `==` and `===` in JavaScript?

What is the difference between `==` and `===` in JavaScript?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are writing a new feature that needs to compare two values to see if they are equal.

You are not sure whether to use the == operator or the === operator.

The Challenge

Explain the difference between the == and === operators in JavaScript. What are the pros and cons of each approach, and which one would you choose for this use case?

Wrong Approach

A junior engineer might think that they are interchangeable. They might not be aware of the difference between type coercion and strict equality.

Right Approach

A senior engineer would be able to provide a detailed explanation of the differences between `==` and `===`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.

Step 1: Understand the Key Differences

OperatorDescription
==The loose equality operator. It compares two values for equality, after converting both values to a common type.
===The strict equality operator. It compares two values for equality, without any type conversion.

Step 2: Choose the Right Tool for the Job

For our use case, we should use the === operator. This is because it is more predictable and less error-prone than the == operator.

Step 3: Code Examples

Here are some code examples that show the difference between the two approaches:

==:

console.log(1 == '1'); // true
console.log(true == 1); // true
console.log(null == undefined); // true

===:

console.log(1 === '1'); // false
console.log(true === 1); // false
console.log(null === undefined); // false

When to use ==

You should almost never use the == operator. The only exception is when you want to check if a value is null or undefined.

if (myVar == null) {
  // This will be true if myVar is null or undefined.
}

Practice Question

What will `[] == ![]` return?