Reputation: 153
Can someone please explain why this JavaScript is interpreted two different ways?
This:
var testnum = $("<div>00000001</div>").text();
var test = "claimid:" + + testnum;
alert(test);
This throws an alert that displays: claimid:1
Where this:
var testnum = $("<div>00000001</div>").text();
var test = "claimid:" + testnum;
alert(test);
This throws an alert that displays: claimid:00000001
I get the reason as to why the second treats testnum as a string, but why does it treat testnum as a number on the first.
Upvotes: 1
Views: 70
Reputation: 27247
In the first case, + is interpreted as the unary positive operator. Consider x = -5
. The - is the unary negative operator. + takes a value and returns its numeric value.
Upvotes: 1
Reputation: 83366
but why does it treat testnum as a number on the first.
Remember, in JavaScript, +
can be used as a unary operator to convert a string to a number. That's what you have here with the second plus sign:
var test = "claimid:" + + testnum;
// ^ HERE
In either case, the string concatenation takes higher precedence than numeric addition (where applicable), but the first case converts your value of 00000001
to a number, which is why a plain old 1
is displayed.
Upvotes: 1
Reputation: 141907
You have two plus signs. The second plus sign is the unary plus operator, which in Javascript has the sole purpose of converting it's operand to a Number.
Upvotes: 4