Just saw this in underscore's source:
if (obj.length === +obj.length) { ... }
What does the plus
do? I never saw this before.
Is it considered a good practice among developers?
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator.
Addition (+) The addition operator ( + ) produces the sum of numeric operands or string concatenation.
The plus(+) sign before the variables defines that the variable you are going to use is a number variable.
The unary plus operator ( + ) precedes its operand and converts it into a number. If it fails to convert the operand into a number, then it returns NaN.
The plus converts a string to a float. The code you provided is equivalent to the following:
if ( obj.length === Number(obj.length) ) { // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With