Why when I use this: (assuming i = 1
)
divID = "question-" + i+1;
I get question-11 and not question-2?
JavaScript (+) sign concatenates instead of giving sum? The + sign concatenates because you haven't used parseInt(). The values from the textbox are string values, therefore you need to use parseInt() to parse the value.
To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks.
When you say prompt() it returns a string by default, so 12+12 is added like a string. You must cast the value to a number type and you can either use Number(prompt()) or parseInt(prompt()). Strings see '+' as concatenating operator.
Both addition and concatenation use the same + operator, but they are not same. Concatenation is used to concatenate i.e. add strings, whereas simple addition adds numbers.
You may also use this
divID = "question-" + (i*1+1);
to be sure that i
is converted to integer.
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:
(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 in 2
"question-" + 2
: since "question-"
is a string, we'll do concatenation, resulting in "question-2"
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With