AppDividend
Latest Code Tutorials

Javascript Object Is Example | Object.is() Tutorial

0

Javascript Object Is Example | Object.is() Tutorial is today’s topic. Javascript Object.is() method determines whether two values are the same value. Object.is() method was introduced in ES2015. It aims to help to compare values.

Javascript Object Is Example

The Object.is() decides whether two values are the same value. Two values are the same if one of the following holds,

  • both are undefined
  • both are null
  • both are true or both false
  • both strings are of the same length with the same characters in the same order
  • both are the same object (means both objects have the same reference)
  • both numbers are and
    • both +0
    • both -0
    • both NaN
    • or both non-zero and both not NaN and both have the same value

The syntax of Javascript Object.is() method is following.

Object.is(value1, value2);

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

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

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

Let’s see the example.

// app.js

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

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

The output is following.

 

Javascript Object Is Example | Object.is() Tutorial

Both variable’s 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 following.

 

Object.is() Tutorial

Now, 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 is going to 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 value and reference are the same. That is why it gives true.

Finally, see some 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 following.

 

The Object is() method

Finally, Javascript Object Is Example | Object.is() Tutorial is over.

Leave A Reply

Your email address will not be published.

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