tags:

views:

34

answers:

1

I have seen a syntax such as the following before:

var mynum = new Number();
var temp = (+mynum);  //this line is what i am curious about
var text = temp.toPrecision(3);

Can anyone tell me what this + syntax means? What I have found is that in some JS implementations, it is somehow necessary as it ensures that the number defined in mynum is valid.

Thanks, jml

+3  A: 

+ is a unary operator which is used to coerce data types into numbers. Unary meaning it only needs one operand.

new Date returns an object, applying + coerces it into a timestamp eg 1277504628812

new Number returns an object, applying + coerces it into the numeric literal 0.

See: http://bclary.com/2004/11/07/#a-11.4.6

This is the ECMAScript documentation, which is the subset of Javascript, in HTML format.

meder
I can't say I understand why that's needed when the previous line is declaring "mynum" to be of type Number.
desau
The person was probably just being real explicit I suppose, I doubt there's any sort of bug in JScript ( MS implementation ) seeing as how those are very trivial statements.
meder
If `mynum` were a string, then `(+mynum)` makes it a number.
Pointy