document.getElementById("demo").innerHTML Error

let intrestrate = 0.3;
intrestrate = 1;
console.log(intrestrate);
let age = 20 ;
console.log(age);
document.getElementById(“demo”).innerHTML = “The total is” + intrestrate + age;
var z = intrestrate + age;
document.getElementById(“Hello”).innerHTML = "The total is " + z;
alert( "The total is " + z);

Basically all above is my coding. The first one in which I have displayed the total in the div id “demo”, the answer is 120 while in the second one in which the total is displayed in the div id “Hello”, the answer is 21 which is the correct answer. Can anyone please explain why is the first one answer not coming correct ??

Note: I have not shown my html coding. I have only made the div ids in it and thats all. Nothing else is written in my html coding.

I’m sorry, I don’t really understand your explanation. I’m also confused - Are you saying that you haven’t written any HTML code? If you have, we need to see that. If you haven’t, then that’s your problem.

You don’t really say what the error with document.getElementById(“demo”).innerHTML is.

I’m assuming that it is some kind of null pointer exception. If document.getElementById(“demo”) returns undefined (in other words, it can’t find that id in the document) then the .innerHTML will throw an error because you cannot access properties on a null or undefined. (Technically you can’t on any primitive, but the others have object wrappers that prevent NPEs.)

Can you log out document.getElementById(“demo”)?

Hello @Seema987, welcome to the forum.

innerHTML will treat its content as a string (technically a DOMstring).

In JS the + operator changes behavior according if it’s a number or a string.
So

"1"+"2" = "12"
// while
1+2 = 3

So I assume when you say the first one is not correct I assume you are wondering why the arithmetic sum is not correct?

Because in the first one you are concatenating string, in the second one you are showing a number (it was already calculated as number).

Hope it helps :sparkles:

Right, after reading Marmiz’ answer, that seems like the correct one.

As an experiment, you could try:

document.getElementById(“demo”).innerHTML = “The total is” + (intrestrate + age);

to see the difference.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.