trenccan
trenccan

Reputation: 720

Add string to a number in Javascript

I have function addNumber and if I click on button with specific value, the value is concatenate to variable b. But if the value of "a" is other than number, the function doesn't work. What am I missing? I thought that the function works with parameter "a" as if it was a string. Otherwise the number were add up. So if b=0, a=x; the result of b=b+a will be x.

function addNumber(a) {
    b=b+a;
    document.getElementById("result").innerHTML= b;
}

I think that problem is here.

function addNumber(a) {

document.getElementById("result").innerHTML= String(a);
}

If the parameter "a" is number, it returns number, but if the parameter "a" is equals some string, returns nothing. Why?

Upvotes: 1

Views: 93

Answers (2)

ashishmaurya
ashishmaurya

Reputation: 1196

If you want to add 2 numbers then you need to parse string into number before adding. parseInt is used for parsing string to integer.

If its not parsed then it will be treated as string and + will act as concatenation operator

Upvotes: 1

Mureinik
Mureinik

Reputation: 310983

If you want to treat both variables as strings, you could explicitly cast them as such:

function addNumber(a) {
    b = String(b) + String(a);
    document.getElementById("result").innerHTML= b;
}

Upvotes: 2

Related Questions