Undefined Variable
I'm working on building a calculator app with little knowledge of JS (jumping into an example to force myself to learn).
What I'm trying to do is take an input and add to a variable 'total'. Currently, the variable 'total' is undefined. Based on button click, it gets defined by whichever number is pressed. However, when outputting, it pre-fixes with 'undefined' despite being defined prior to output (see attachment)
How could I go about fixing this?
![No description](https://cdn.answeroverflow.com/1149424574572793966/image.png)
12 Replies
I think the problem is probably this line: 0 an empty string or "0".
Yeah, if you do this on the console you'll see the same behavior:
You can solve this by initializing
total = total + btns[i].id;
Since total is undefined, you are trying to add undefined
and something else which I is likely causing the issue. Try to initialize total to total
to an actual value, like an empty string since this is actually a string and not a numerical number (at least not at this point).Ah okay, that makes sense thank you
because you do
total = total +
so the new one is added to the undefined
or make a check if total is undefined
if so do then total =
instead of total +=
Now that I defined total to 0, it prefixes with a 0. Do I need to by default remove the first index of the input because of this ? or is there another way around it
Just initialize to an empty string
let total = ""
Do you still do
total +=
@-MattYeah, I'm assuming it would be the same output anyways because that's just a shortcut?
Make's sense I was gonna have to use string anyways to do the calculations
when the first input you need to overwrite . not add
It needs to add because of each input
to do calculation as a calculator
Then you can better use a empty string
yeah im doing that now and it works 👍 i figured undefining would act similarly tbh
thank you guys
YW