Javascript assertion I haven't seen before
if (length === +length)
It guarantees that it length
is actually a numeric value.
Two things to understand here,
-
The strict equality operator will
true
only evaluate when the objects are the same . In JavaScript, numbers and strings are immutable. Thus, when you compare two numbers, the Number values will be compared. -
The unary operator
+
will try to get the numeric value of any object. If the object already has a typeNumber
, it won't make any changes and return the object as it is.
In this case, if length
is actually a number in string format, say the "1"
expression
"1" == +"1"
will evaluate as true
because it is "1"
forcibly bound to numeric 1
internally and compared. But
"1" === +"1"
which will be converted to
"1" === 1
and it won't be coerced, and since the types are different, it ===
will be evaluated before false
. And if it length
has any other type, ===
it will immediately return return false
, since the right side will be a number.
You can think of this check as a shorthand version of this
if (Object.prototype.toString.call(length) === "[object Number]")
source to share
This is a way to check if a value is numeric. See for example:
> length="string"
> length === +length
false
> length=2
> length === +length
true
Unary +
converts the variable length
to type Number, so if it was already numeric, then the identifier will be executed.
Using the identity operator ===
rather than the equality operator ==
is important here because it strictly compares both the value and the type of the operands.
Perhaps a more explicit (but slightly longer to write) way of doing the same test is to use:
typeof length === "number"
source to share