element. This indicates a math operation and tries to convert the element to
a number. If the conversion fails, it will evaluate to
This is especially useful when one wants to convert a string to a number
quickly, but can also be used on a select set of other types.
The unary + operator, when used on types other than string, will internally
attempt to call
(in that order) and then attempt to convert the result to a number. Thusly,
the unary + operator can successfully convert many of the native JS types
with certain restrictions:
Values that are of type and value undefined will be converted to
NaN. There are select cases where a value of type undefined
will be converted to 0 such as in the
new Array(1) example.
The unary + operator will convert null values to 0.
The first element in a literal array will be converted if there is only one element in the array and the value is of convertible type.
If the Array constructor is used and passed a value of 1, an Array of size 1 is constructed. In this case, the unary operator will return a 0, as the Array has a single element of type undefined.
All boolean values, whether literal or created with the Boolean constructor, can be converted to numbers (0 for false, 1 for true) by the unary + operator.
Values of type Date will be converted to their corresponding numerical
valueOf()), which is the number of milliseconds
since the UNIX epoch.
Using the unary operator on an object literal will yield NaN because by
default there are no
methods for an object literal.
It is possible to use the Object constructor, passing a convertible value and then using the unary operator to convert the value to a number.
Both a string literal and a string created using the String constructor will be converted to numbers by the unary operator if the string contains only numerals (optionally with a single '-' at the front and a single '.' after one or more numerals) or is empty. An empty string will be converted to the number 0.
The unary + operator has the same precedence as the other unary operators as described by MSDN.
The unary + operator is the most useful when one needs to convert a string into a number, which happens often during the course of web development. For instance if one retrieves a value from an input box using the .value property, the value will be a string type. If one then wants to perform an addition of the value with another value, string concatenation will take place, thus it is necessary to convert to a number. One simple way of accomplishing this is to use the unary + operator as shown here:
var nInitial = document.getElementById("initialField").value; var nExtra = 15.5; var nTotal = +nInitial + nExtra; document.getElementById("totalField") = nTotal;
There may be other obvious applications for this operator as well. If you think of any, let me know.