3 min read

Differences Between Object.is and ===, Array .at() and Direct Indexing with [ ], and substring and slice

Table of Contents

Understanding the Differences Between Object.is and === for Comparing Values in JavaScript

The Object.is() static method compares two values to check if they are strictly equal. In most cases, it works the same as the strict equality operator ===.

However, there are two key differences:

Comparison of NaN

With ===, comparing NaN to NaN results in false, but with Object.is(), NaN is considered equal to NaN.

NaN === NaN
// false

Comparison of +0 and -0

In short: === considers +0 and -0 equal, while Object.is() considers them not equal. Example code:

+0 === -0
// true

Object.is(+0, -0)
// false

The difference between the at method and direct array indexing

Given an array arr = [1, 2, 3], both of the following methods will return the second element of the array:

const arr = [1,2,3];
console.log(arr.at(1), arr[1]);
// result:2 2

Now, here’s the question: what’s the difference between using the at() method and directly using an index to access an array element?

The key difference arises when the parameter or index value is negative. Let’s take a look at an example:

const arr = [1,2,3];
console.log(arr.at(-1), arr[-1]);
// reuslt:3 undefined

Here’s how it works: when the parameter of the Array.prototype.at() method is a negative number, the parameter value is calculated by adding the negative number to the array’s total length.

In the example above, arr.at(-1) is equivalent to arr.at(-1 + 3) => arr.at(2) => 3. This is how the final result of 3 is obtained.

If the absolute value of the negative number is greater than the array length, or if the parameter is a positive number that exceeds the array bounds, undefined will be returned. This results in the following behavior in the code.

const arr = [1,2,3];
console.log(arr.at(-4), arr[-4]);
// result:undefined undefined

console.log(arr.at(3), arr[3]);
// result:undefined undefined

The differences between substring() and slice()

The substring() and slice() methods for strings are usually interchangeable for copying strings.

However, there are differences in the following two scenarios:

  • When substring() receives negative parameters, they are treated as 0. slice(), on the other hand, allows negative parameters, such as:
'Hello World!'.substring(-2)
// result: 'Hello World!'

'Hello World!'.slice(-2)
// result: 'd!'
  • When the first parameter of substring() is greater than the second, it automatically swaps their positions. In contrast, when the first parameter of slice() is greater than the second, it returns an empty string, as shown below:
'Hello World!'.substring(4, 2)
// result: 'll'

'Hello World!'.slice(4, 2)
// result: ''

If you’re unsure about the order of the parameters, it’s a good idea to use the substring() method. For other cases, it’s better to use the slice() method, simply because the name is shorter and easier to remember.