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?
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.
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.
The equality operator ( == ) checks whether its two operands are equal, returning a Boolean result.
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.
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).
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)]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With