I have written the following function which should log an array beginning at "0" and ending with the function's argument (in this case "40") to the console.
function range(num) {
var holder = [];
for(var i = 0; i <= num; i++) {
holder.push(i);
return holder;
}
}
console.log(range(40));
This instead logs "undefined". I have noticed however, that removing the for loop's brackets like this:
function range(num) {
var holder = [];
for(var i = 0; i <= num; i++)
holder.push(i);
return holder;
}
console.log(range(40));
causes the function to work correctly, which is great except I do not understand why the function now works. Can anyone explain?
for
without brackets only loops theholder.push()
part. Thereturn
is only excecuted when the loop is done, as it should be. – Cerbrus Jun 23 '14 at 8:03undefined
but[0]
. – deceze♦ Jun 23 '14 at 8:05