Reputation:
Was reading through Douglas Crockford's code here and saw a line
var value = +node.getValue();
but I don't see anything at http://www.w3schools.com/js/js_operators.asp which corresponds to an = +
or a way that +
can be used as a unary operator. So what does this mean?
Upvotes: 3
Views: 87
Reputation: 31
Just to add on to what's been said do the following:
var a = +'4';
var b = '4';
console.log(typeof(a));//Number
console.log(typeof(b));//String
Upvotes: 0
Reputation: 3342
It's just a quick way to make sure the variable is an INT, (vs. a STR or BOOL, e.g.).
Upvotes: 0
Reputation: 48257
The -
and +
operators are both unary in JS and, before forcing the value's sign, must convert the value to a number.
Obviously -
will convert to a number and invert the sign, but +
only does the first part. Running +"100"
will return the number 100
.
This behavior is explicitly stated in the spec at 11.4.6, where the unary +
operator is defined:
The unary + operator converts its operand to Number type.
Upvotes: 7