Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript idiom: What does if (x === +x) do? [duplicate]

Reading through the source code of underscore.js I stumbled upon the following line:

... if (obj.length === +obj.length) { ...

That's a bit confusing for me. What is actually being compared here? I believe it has something to do about detecting native arrays, but cannot figure out what's actually going on. What does the + do? Why use === instead of ==? And what are the performance benefits of this style?

like image 603
Saintali Avatar asked Feb 18 '23 12:02

Saintali


2 Answers

The + coerces the value to an Number (much like !! coerces it to a boolean).

if (x === +x)

...can be used to confirm that x itself contains an integer value. In this case it may be to make sure that the length property of obj is an integer and has not been overwritten by a string value, as that can screw up iteration if obj is treated as an array.

like image 163
Explosion Pills Avatar answered Feb 20 '23 03:02

Explosion Pills


It is a silly (IMO) way of checking if obj.length is a Number. This is better:

typeof obj.length == "number"
like image 21
Salman A Avatar answered Feb 20 '23 03:02

Salman A