I was perusing the underscore.js library and I found something I haven't come across before:
if (obj.length === +obj.length) { ... }
What is that +
operator doing there? For context, here is a direct link to that part of the file.
I was perusing the underscore.js library and I found something I haven't come across before:
if (obj.length === +obj.length) { ... }
What is that +
operator doing there? For context, here is a direct link to that part of the file.
It's a nice hack to check whether
obj.length
is of the typenumber
or not. You see, the+
operator can be used for string coercion. For example:This is possible because the
+
operator coerces the string"3"
to the number3
. Hence the result is10
and not"37"
.In addition, JavaScript has two types of equality and inequality operators:
3 === "3"
expresses false).3 == "3"
expresses true).Strict equality and inequality doesn't coerce the value. Hence the number
3
is not equal to the string"3"
. Normal equality and inequality does coerce the value. Hence the number3
is equal to the string"3"
.Now, the above code simply coerces
obj.length
to a number using the+
operator, and strictly checks whether the value before and after the coercion are the same (i.e.obj.length
of the typenumber
). It's logically equivalent to the following code (only more succinct):It's a way of ensuring that obj.length is a number rather than a potential string. The reason for this is that the === will fail if the length (for whatever reason) is a string variable, e.g. "3".
The unary
+
operator can be used to convert a value to a number in JavaScript. Underscore appears to be testing that the.length
property is a number, otherwise it won't be equal to itself-converted-to-a-number.According to MDN: