How to Check If Two Same Values in Object

0
62
Javascript Object Is Example | Object.is() Demo Tutorial

The Object.is() method was introduced in ES2015. It aims to help to compare values.

JavaScript Object Is

JavaScript Object is() a built-in function that checks whether two values are the same. Two values are the same if one of the following holds:

  1. both are undefined
  2. both are null
  3. both are true or both false
  4. both strings are of the same length with the same characters in the same order
  5. both are the same object (which means both objects have the same reference)
  6. both numbers are and
    1. both +0
    2. both -0
    3. both NaN
    4. or both non-zero and both not NaN, and both have the same value

Syntax

The syntax of the Object.is() method follows.

Object.is(value1, value2);

Parameters

The value1 parameter is required and is the first value to compare.

The value2 parameter is required and is the second value to compare.

Return value

It returns the boolean value indicating whether or not the two arguments are the same.

Example

// app.js

let a = 'app'
let b = 'app'

console.log(Object.is(a, b))

The output is the following.

Javascript Object Is Example | Object.is() Tutorial

Both variables’ value is the same. So it returns a true.

Let’s compare the undefined and null.

let a = null
let b = undefined

console.log(Object.is(a, b))

The output is the following.

Object.is() Tutorial

Let’s compare two empty arrays and see the output.

// app.js

let arrA = []
let arrB = []

console.log(Object.is(arrA, arrB))

Javascript Object Is Example

See, the output is false.

Now, check for the objects.

// app.js

let objA = {}
let objB = {}

console.log(Object.is(objA, objB))

The output is, of course, false.

Okay, see the following example.

// app.js

let objA = {a: 1}
let objB = {a: 1}

console.log(Object.is(objA, objB))

We have defined the same values of the objects, but the reference is different; that is why it will output false.

See the following scenario.

// app.js

let objA = {a: 1}
let objB = {a: 1}

console.log(Object.is(objA, objA))

In this case, we will get true because the value and reference are the same. So that is why it is true.

Finally, see the following cases.

// app.js

console.log(Object.is(undefined, undefined))
console.log(Object.is(null, null))
console.log(Object.is(0, -0))
console.log(Object.is(-0, -0))
console.log(Object.is(NaN, 0/0))

The output is the following.

The Object is() method

That’s it.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.