Javascript assertion I haven't seen before

I am validating Javascript code written in UnderscoreJS. In this case, there are several examples of writing JS code like this:

if(length === +length){ //do something} 

      

or

if(length !== +length){ //do something }

      

What exactly does it calculate? I've never seen this before.

+3


source to share


2 answers


if (length === +length)

      

It guarantees that it length

is actually a numeric value.

Two things to understand here,

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]")

      

+9


source


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"

      

+3


source







All Articles