emisqwe emisqwe - 1 year ago 89
Node.js Question

The + + operator in javascript

When I have one plus, I get the wrong answer e.g.

var b = [069];
var total = 0;

total = total + b
console.log(total) // total = 069

However, when I add a second plus so the equation looks like this

total = total + + b // total = 69

I get the correct answer of 69. The above is just a simplified example of my issue.

This works fine, however whilst using JSHint I get a warning saying

confusing pluses

How can I get the correct answer without using the + + ? Also, what is this operator called?

Answer Source

Posting my comment as an answer

+ in front of a variable would cast it to a number if I'm correct.

Try this in your console:

"5" would return "5" (string), where

+"5" would return 5 (number).

You could use total = parseInt(total) + parseInt(b); to get a correct result, as parseInt() would try to make a number out of any input parameter it gets.

Theoritecally, you could just parse the total as a number, but it would be prone to an error like "1" + "0" = "10" resulting in 10, which should mathematically be 1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download