3

Possible Duplicate:
How do I Convert a String into an Integer in JavaScript?

Given the following code:

var n = '1';
var x = n + 2;

x is set to "12".

Assuming I cannot change the value of n, what the most efficient way to have x set to 3?

Is it necessary to use parseInt() here? Or is there a way to have JavaScript automatically treat the digit as a number?

Community
  • 1
  • 1
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • If you are using parseInt() dont forget the second parameter 10 like parseInt(n,10) – Saju Jan 08 '13 at 20:32
  • The suggested duplicate is not an exact duplicate. As my question points out, I already know about `parseInt()`. My question is if there is a way to simply have JavaScript treat the digit to be a number in the way it treated a number as a digit in the code example in my question, without explicitly parsing the string. – Jonathan Wood Jan 08 '13 at 20:43

2 Answers2

4

parseInt(n,10) would work. You can also do n^0 as a shortcut. In fact, there are several such shortcuts available, but parseInt is "best" because it's more obvious to a human reader.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
4

You can add + before n, this way it will parse it to a number.

var x = +n + 2;
Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82