Why this code doesn\'t work
function callback(num, func) {
for(var i = 0; i < num; i++) {
func();
}
}
callback(4, console.log(\"Hello
Because functions are first-class citiziens in Javascript (meaning functions can be stored in variables). passing a function as an argument will return a reference to the function definition rather than the function call you're trying to invoke. It does however evaluate your console.log beforehand and passes it on as a variable and since your log's function call doesn't return anything it passes undefined to your callback function.
function test( logFunction ){
logFunction( 'test' )
}
test( alert )
Is an example of this behaviour. It's also the reason closures like the one demonstrated by Remy J work.
function callback(num, func) {
for(var i = 0; i < num; i++) {
func( "Hello" );
}
}
callback(4, alert);
This would work.