While looking at the jslint code conventions I saw this line:
total = subtotal + (+myInput.value);
What is the purpose of the second '+'?
While looking at the jslint code conventions I saw this line:
total = subtotal + (+myInput.value);
What is the purpose of the second '+'?
The unary plus is there for completeness, compared with the familiar unary minus (-x). However it has the side effect, relied upon here, of casting myInput.value into a Number, if it's something else such as a String:
alert(1+'2'); // 12
alert(1+(+'2')); // 3
That's called the "unary + operator", it can be used as a quick way to force a variable to be converted to a number, so that it can be used in a math operation.
The + is to typecast it to a number as others have said. It's needed there because form inputs are always string values, and adding a string to another variable concatenates them together into a new string, even if the string looks like a number.
The unary plus operator is, arithmetically speaking, a noop. But like all other purely arithmetic operators, it will convert its argument to JavaScript's number type and can therefore be used as a shorthand for an explicit cast.
Explicit type casting in JavaScript is done via calling the appropriate constructor functions without using the new
operator.
For example,
Number(foo)
will convert foo
to a primitive of type number, whereas new Number(foo)
would additionally create a wrapper object for the primitive and is therefore equivalent to
Object(Number(foo))
Similar to this use of +
is the use of !!
to convert to boolean type.