1

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?

5
  • 1
    b = parseInt(b) ? b + a : a Commented Aug 23, 2015 at 7:34
  • isn't it supposed to add the number? Commented Aug 23, 2015 at 7:34
  • are you using parseInt to convert in to a number? Commented Aug 23, 2015 at 7:34
  • But what exactly you want. Answer these! 1. if b=10 and a=10 Result=20; 2. If b=0 and a=x Result=?? 3. b=a and a= s or ss..ssss.. etc., Result=?? Commented Aug 23, 2015 at 7:46
  • if b=1 and a=2 Result=12, If b=1 and a=x Result=1x. Commented Aug 23, 2015 at 7:50

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

this works but what I want to do is concatenate 2 or more numbers. Im making calculator. If I click on button 1, result will be 1, if I click than on 2, the result will be 12. Now it is working but if I click for instance on comma sign, it doesn't return 12, .
Javascript is a loose type language, so nothing stop you from passing illegal types. Since you are making a calculator, you should check if the input is from 0~9 first, if it is then call addNumber if it's not then do something else.
1

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

1 Comment

Yes I understand. I want to concatenate numbers, but sometimes I want to concatenate number with string and the function above is working good when the a parameter represent number, but if it is a string, it doesn't concatenate the number and string together as I expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.