Javascript (+) sign concatenates instead of giving sum of variables
Solution 1:
Use this instead:
var divID = "question-" + (i+1)
It's a fairly common problem and doesn't just happen in JavaScript. The idea is that +
can represent both concatenation and addition.
Since the + operator will be handled left-to-right the decisions in your code look like this:
-
"question-" + i
: since"question-"
is a string, we'll do concatenation, resulting in"question-1"
-
"question-1" + 1
: since"queston-1"
is a string, we'll do concatenation, resulting in"question-11"
.
With "question-" + (i+1)
it's different:
- since the
(i+1)
is in parenthesis, its value must be calculated before the first+
can be applied:-
i
is numeric,1
is numeric, so we'll do addition, resulting in2
-
-
"question-" + 2
: since"question-"
is a string, we'll do concatenation, resulting in"question-2"
.
Solution 2:
You may also use this
divID = "question-" + (i*1+1);
to be sure that i
is converted to integer.
Solution 3:
Use only:
divID = "question-" + parseInt(i) + 1;
When "n" comes from html input field or is declared as string, you need to use explicit conversion.
var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);
If "n" is integer, don't need conversion.
n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;