Skip to main content Accessibility Feedback

The method in vanilla JS

Today, we’re going to look at the method: what it does, how it works, and when you might want to use it. Let’s dig in.

What the method does

The method checks if two values are the same, and returns a boolean: true if they’re the same, and false if they’re not.

You pass the two values in as arguments.

// returns true, 42);

// returns false'orange', 'blue');

How the method works

It works mostly like the strict equals operator, but with a few small differences we’ll get into in just a bit.

Just like with strict equals, it does not check if two arrays or objects have the same value. It checks if they’re the same object.

let wizards = ['Gandalf', 'Radagast', 'Merlin'];
let otherWizards = wizards;

// Since otherWizards is just a reference to wizards
// returns true, otherWizards);

// Because we've created an immutable copy
// returns false, [...wizards]);

For strings and numbers, which are always immutable, it checks the value.

let num1 = 42;
let num2 = 42;

// returns true, num2);

One notable way that it differs from strict equals is in how it handles NaN and signed zeroes (a 0 with a + or - symbol).

// returns false
let n = NaN === NaN;

// returns true, NaN);

// returns true
let z = 0 === -0;

// returns false, -0);

Yea, JavaScript is weird!

When should you use this?

I see myself continuing to use strict equals for the foreseeable future, simply because it’s fewer characters and muscle memory for me to type.

When doing a comparison where NaN or a signed zero might be one of the values and you want to the behavior described above, however, might be a better choice. That feels very situational to me, though.