Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript numeric self equality [duplicate]

I recently came across the following code:

function baseClamp(number, lower, upper) {
  if (number === number) {
    if (upper !== undefined) {
      number = number <= upper ? number : upper;
    }
    if (lower !== undefined) {
      number = number >= lower ? number : lower;
    }
  }
  return number;
}

The conditional at the beginning of the function is interesting.

  if (number === number) {

I tested the following in Chrome:

var number = undefined;
number === number
true
number = null
number === number
true
number = NaN
number === number
false

Does number === number simply check for NaN or is there more to it?

like image 582
Hakkar Avatar asked Sep 14 '16 15:09

Hakkar


People also ask

Are strict equal identical?

Strict equality using ===Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal.

What is=== operator in JavaScript not equality Comparison operator strict equality Comparison operator equality operator Comparison operator?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

How to check if something is equal in JavaScript?

The equality operator ( == ) checks whether its two operands are equal, returning a Boolean result.

What is double equal in JavaScript?

With double equals, JavaScript will convert the types of the two values to be exactly the same before doing an equality check. This means that if you have the following code 1 == '1' then JavaScript will convert the string '1' into a number so that the equality check is comparing two numbers.


2 Answers

number === number simply checks if number is not NaN. NaN is the only value which is not equal to itself.

number === number can be replaced with !Number.isNaN(number) in modern browsers (see MDN docs).

like image 62
Michał Perłakowski Avatar answered Sep 29 '22 05:09

Michał Perłakowski


NaN is the only value in ECMAscript that does not equal itself.

This function is equivalent to Math.min(Math.max(number, lower), upper) and seem to behave the same. It will skip any processing if number is NaN.

function baseClamp(number, lower, upper) {
  if (number === number) {
    if (upper !== undefined) {
      number = number <= upper ? number : upper;
    }
    if (lower !== undefined) {
      number = number >= lower ? number : lower;
    }
  }
  return number;
}

function mathClamp(number, lower, upper) {
  return Math.min(Math.max(number, lower), upper);
}

console.log([-10, 0, 10, NaN].map(it => [baseClamp(it, 0, 10), mathClamp(it, 0, 10)]));
like image 37
ssube Avatar answered Sep 29 '22 06:09

ssube