Reputation: 5095
I am inspecting some Javascript code written in UnderscoreJS. In this, there are quite a few instances of JS code being written like this:
if(length === +length){ //do something}
or
if(length !== +length){ //do something }
What exactly does this compute to? I have never seen this before.
Upvotes: 3
Views: 102
Reputation: 239653
if (length === +length)
It makes sure that the length
is actually a numeric value.
Two things to understand here,
The Strict equality operator, will evaluate to true
only when the objects are the same. In JavaScript, the numbers and strings are immutables. So, when you compare two numbers, the Number values will be compared.
Unary +
operator will try to get the numeric value of any object. If the object is already of type Number
, it will not make any changes and return the object as it is.
In this case, if length
is actually a number in string format, lets say "1"
, the expression
"1" == +"1"
will evaluate to be true
, because "1"
is coerced to numeric 1
internally and compared. But
"1" === +"1"
which will be transformed to
"1" === 1
and that will not undergo coercion and since the types are different, ===
will evaluate to false
. And if length
is of any other type, ===
will straight away return false
, as the right hand side is a number.
You can think of this check as a shorthand version of this
if (Object.prototype.toString.call(length) === "[object Number]")
Upvotes: 9
Reputation: 74695
It is a way of testing whether a value is numeric. See this for example:
> length="string"
> length === +length
false
> length=2
> length === +length
true
The unary +
converts the variable length
to the Number type, so if it was already numeric then the identity will be satisfied.
The use of the identity operator ===
rather than the equality operator ==
is important here, as it does a strict comparison of both the value and the type of the operands.
Perhaps a more explicit (but slightly longer to write) way of performing the same test would be to use:
typeof length === "number"
Upvotes: 3