How to check the equality of 2 values in Javascript? (If they are the same)

About

This page discusses Equality between 2 Javascript values. Because every value in javascript is an object, it applies also to the object.

Method

Object.is

Object.is verifies the value.

  • in case of the primitive, this is the value
  • in other cases, this is the reference

This is the function used by libraries to check if 2 values received are the same. (React uses it intensively)

Syntax:

Object.is(value1, value2);
let foo = { a: 1 };
let bar = foo;
console.log(Object.is(foo, foo));              // true
console.log(Object.is(foo, bar));              // true
console.log(Object.is(foo, { a: 1 }));              // false
  • Special Values
Object.is(null, null);            // true
Object.is(undefined, undefined);  // true
Object.is(window, window);        // true

Operator

For a comparison:

  • between object, both == and === object equality operator will simply check whether the references match.
  • if one side of the equality comparison is not an object, valueOf is called before any comparison

For objects, they will not compare the content (ie not anything about the underlying values).

Equality Operator Example

Object

function Employee(name) {
    this.name = name;
    this.dept = 'general';
    this.valueOf = function(){
        return this.name;
    };
}
let employee1 = new Employee('foo');
let employee2 = new Employee('foo');
  • Test
console.log("The variable employee1 has the type "+(typeof employee1 ));
console.log("The variable employee1 has the valueOf "+employee1.valueOf());
console.log("They are not equal "+(employee1 == employee2));
console.log("But their value is "+(employee1.valueOf() == employee2.valueOf()));

Array

var a = [1,2,3];  
var b = [1,2,3]; 
console.log("The array a has the type "+(typeof a));
console.log("The array a in a string format is "+a.toString()+ "( valueOf() )" );
  • The string representation of an array is element1, …, elementn
var c = "1,2,3"; 
console.log("The variable c has the type "+(typeof c));
  • Equality
console.log("\nEquality");
console.log( a == c ); // true - same value as string
console.log( b == c ); // true - same value as string
console.log( a == b ); // false (not the same reference)





Discover More
Javascript - Object

object in javascript An object is a data type in Javascript. An object follows a json data structure with key that holds property value. The value may be of a variable or a function In JavaScript, a...
Javascript - Set

The Set interface represents a set data type and works only with primitive type as there is no way to define an object equality function. object Jsdoc Declaration Add/Delete Size Contains...
React - Memo (Cache)

Memoization is a React caching function that caches a computed value. It save the results of computation, and reuse these results if it sees the same inputs later. React memo is the equivalent...



Share this page:
Follow us:
Task Runner