crescentfresh crescentfresh - 7 months ago 22
Javascript Question

Why is my function outputting 0 (zero)?

This code is supposed to calculate two user inputs by multiplying them. However, the output is consistently 0 instead of would normally be expected ie 5*5=0. I am not sure why this is happening. Am I not passing the variables into the function correctly? I feel like I might not be properly understanding value vs. reference (I am currently learning javascript)

var x = document.getElementById("a").value;
var y = document.getElementById("b").value;
var button = document.getElementById("button");

button.addEventListener('click', function() {
calculator(x,y);
}, false);

function calculator(a,b) {
var output = a * b;
document.getElementById("answer").innerHTML = output;
console.log(output);
}

Answer

Omit the value capture, just grab the elements:

var x = document.getElementById("a");
var y = document.getElementById("b");

Then use the values as the function parameters.

button.addEventListener('click', function() {
  calculator(x.value, y.value);
}, false);

You were grabbing the values when they were empty and passing those to the function.

DEMO