According to your comment, and updated question, you are calling the function from a form's inline event handler:
onsubmit = "calculate()"
You don't pass any arguments to the function, which means within the function both firstNum
and secondNum
are undefined
. I think you are confusing them with your global variables of the same name.
If you changed the function declaration to remove the parameters:
function calculate() {
...then within the function when you reference firstNum
and secondNum
it would use the global variables. (Or you could change the parameter names, but since you don't actually pass any parameters in it makes more sense to remove them.)
Demo: http://jsfiddle.net/5WBB5/
Note that it is normal practice to declare variables that are only used within a function inside that function:
function calculate() {
var firstNum = 1;
var secondNum = 2;
var list = [];
for (var i = firstNum; i <= secondNum; i++) {
list.push(i);
}
console.log(list);
};
(Notice that that has the same output: http://jsfiddle.net/5WBB5/1/)
If you need the function to make use of different functions then you declare parameters as in your code but pass values in when you call the function:
function calculate(firstNum, secondNum) {
// your code here
}
calculate(1, 2);