Declaring global variable in JS outside of function not working

I was trying to declare variables from two input fields that I would reuse for several functions in a basic calculator. I keep getting an error message from the console that it can’t read the value of null. I was hoping to avoid copy pasting the same declarations inside each function.


//var n1 = 4;
//var n2 = 2;
var n1 = document.getElementById(‘num1’).value
var n2 = document.getElementById(‘num2’).value

function divide(){
var quotient = n1/n2;
document.getElementById(“result”).value = quotient;

function sub(){
var difference = n1 - n2;
document.getElementById(‘result’).value = difference;


What’s your html look like?

Better yet, can you share a link to your demo on a codepen?

Sure thing, here’s a code pen.

You are grabbing values from input boxes straight out of the box, which is empty when script is first loaded.

You want to grab those values only when you want to. In this case any operand button is clicked. This is where an event listener comes in. You can listen for when + button is clicked, grab the values of input boxes.

Take a look at this example.

Good luck!