I’m curious about what I’m not understanding in this code snippet…
Why does this work?
function insert_number(number){
var output = document.getElementById('output');
output.value += number.value;
}
but this doesnt work?
var output = document.getElementById('output');
function insert_number(number){
output.value += number.value;
}
Does it have something to do with the way the variable output is defined?
Also how would I write the output variable within the function insert_number() while still making output available to all other functions in my script (even if it means having to escape the variable out of the function, or specifically send it to another function as a parameter)?
Note: All my code is in an external “.js” file
the complete context of the code as of right now is this (I will be adding more later):
var output = document.getElementById('output');
function insert_number(number){
output.value += number.value;
}
function clear_output(){
output.value = "";
}
Actually, they both work, as long as the DOM element at
exists when the code is run. The important difference is that your
insert_numberfunction probably runs after the DOM is loaded, unlike the bare output assignment in the second example.Good JavaScript developers try to avoid global variables where unnecessary, but the simple answer is this: