Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript (+) sign concatenates instead of giving sum of variables

Why when I use this: (assuming i = 1)

divID = "question-" + i+1; 

I get question-11 and not question-2?

like image 350
ilyo Avatar asked May 11 '11 07:05

ilyo


People also ask

Why is my JavaScript concatenating instead of adding?

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.

How do I stop concatenation?

To avoid unexpected string concatenation while concatenating strings, multiple strings, and numbers, use backticks.

Why are my numbers not adding in JavaScript?

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.

Is concatenation the same as addition?

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.


2 Answers

You may also use this

divID = "question-" + (i*1+1);  

to be sure that i is converted to integer.

like image 37
Serafeim Avatar answered Sep 24 '22 07:09

Serafeim


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 in 2
  • "question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".
like image 79
Joachim Sauer Avatar answered Sep 25 '22 07:09

Joachim Sauer