allen.w allen.w - 2 months ago 7
Javascript Question

confused about javascript local variable VS global variable

Here is the code below:



var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;

function Multiplication (num1,num2) {
document.getElementById('result').innerHTML = num1*num2;

}

function Divide (num1,num2) {
document.getElementById('result').innerHTML = num1/num2;
}

<form>
<input type="number" value="2" id="num1"/>
<input type="number" value="3" id="num2" />
<input type="button" value="Multiplication" onClick="Multiplication()"/>
<input type="button" value="Divide" onClick="Divide()"/>
</form>

<div>
<span>The result is:</span>
<p id="result"></p>
</div>





I am getting result NAN when i click the multiplication or divide button to trigger the function,but i thought num1 and num2 both are global variable,could someone help me figure out why the both undefined?

Answer

The are two major problems (and one minor) with your code:

First of all, your functions Multiplication and Divide have two arguments num1 and num2 that shadow the global ones, but you're calling the functions with no arguments, so inside the functions, these will have the value undefined. Multiplying or dividing undefined by itself gives NaN (not a number).

Secondly, even if you remove the arguments from your functions, num1 and num2 are the values of the two fields when the code is running, that is, when the page is loading. So if you change the value in the input fields, pressing the buttons would not give a different result.

Third, your variables num1 and num2 are strings, not numbers, since .value of an input field gives a string. This won't make a difference when you're multiplying or dividing strings, but if you're adding two strings, then '1' + '1' == '11' instead of 2, so you should use Number() to convert your strings into numbers.

Taking these things into account, you'd end up with something like this:

function Multiplication () {    
  var num1 = Number(document.getElementById('num1').value);
  var num2 = Number(document.getElementById('num2').value);

  document.getElementById('result').innerHTML =  num1*num2;
}
    
function Divide () {
  var num1 = Number(document.getElementById('num1').value);
  var num2 = Number(document.getElementById('num2').value);

  document.getElementById('result').innerHTML =  num1/num2;
}
<form>
  <input type="number" value="2" id="num1"/>
  <input type="number" value="3" id="num2" />
  <input type="button" value="Multiplication" onClick="Multiplication()"/>
  <input type="button" value="Divide" onClick="Divide()"/>
</form>

<div>
  <span>The result is:</span>
  <p id="result"></p>
</div>