'document.getElementById("spanid").innerHTML is not working

I'm quite new to javascript, so I can't really find what's wrong in my code. Below is the code:

<script language="javascript">

var x = parseInt(prompt("Enter the first number.",""));
var y = parseInt(prompt("Enter the second number.",""));
var z = prompt("Enter an operation.","");
var total = 0;

switch (z) {
  case "1":
  case "+":
  case "add":
  case "addition":
  case "sum":
    var total = x + y;
    break;
  case "2":
  case "-":
  case "sub":
  case "subtract":
  case "subtraction":
  case "diff":
  case "difference":
    var total = x - y;
    break;
  case "3":
  case "x":
  case "*":
  case "mult":
  case "multiply":
  case "multiplication":
  case "prod":
  case "product":
    var total = x * y;
    break;
  case "4":
  case "/":
  case "divide":
  case "division":
  case "quo":
  case "quotient":
    if (y == 0) {
      document.getElementById("total1").innerHTML = "Error. You cannot divide by 0."
  } else {
    var total = x / y;
  } break;
  default:
    document.getElementById("total1").innerHTML = "There is something wrong with one of your inputs. Please reload the page."
}

if (isNaN(total) == false) {
  document.getElementById("total1").innerHTML = total
}

When I input 0 to the prompt for variable y, it doesn't show "Error. You cannot divide by 0." and instead shows just 0. There is totally a span with the id of total1.

The span id was formerly "total" so I changed it to "total1" but it still did not work..



Solution 1:[1]

The problem is that you declare var total = 0 in the fourth line of your code, and then in each of your cases inside the switch statement you re-declare it. But those variables exist just in the scope of that statement.

So, when your code reaches the final if, it checks if isNan(0) == false, which is not, so it sets the innerHTML to the value of total.

Solution: delete all of the var keywords inside the switch statement and try again.

Solution 2:[2]

Your code works but your span's innerHTML gets replaced by this block:

if (isNaN(total) == false) {
  document.getElementById("total1").innerHTML = total
}

As total is initialized to 0 (and doesn't change for operations like "divide") isNaN(total) results false and that writes total (which in this case remains 0) in your span element.

Besides removing the var keyword (as suggested in JuanDeLasNieves's answer) you should also initialize total as undefined instead of 0:

var total = undefined;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JuanDeLasNieves
Solution 2