Susan Susan - 1 year ago 65
Javascript Question

In javascript if foo is a function, what is the difference between foo() and foo, and how do they differ when passed as args to high-order functions?

I am just starting to learn javascript while reading a book about node.js. In one of the first examples it shows a high-order function:

setTimeout(function () {
console.log('2000 milliseconds have passed since this demo started');
}, 2000);

This works when I run it in the REPL. It waits 2 seconds and then writes the string I gave it.

So I tried doing something that I expected would produce the same output:

setTimeout(console.log('2000 milliseconds have passed since this demo started'),2000);

This printed the string out immediately. I am guessing that the setTimeout still waited and then did nothing at the end of the 2 seconds. It just printed the string out first for some reason.

I played around with it a little more and created another function that just prints a string:

function tester() {
console.log('tester function ran');

I then called this function inside of setTimeout:


It still printed the string in tester() out first and then waited 2 seconds and did nothing else.

I then tried removing the parenthesis:


This "worked". It waited 2 seconds and then printed out the string in tester().

My question now is what is the difference between tester() and tester in this context? And does this mean that I can't pass arguments to a function inside of the high-order function setTimeout()? If so, why?

Answer Source

in case of setTimeout(tester(),2000); you are actually calling the method tester. And since it does not have any callback, it would not do anything.

setTimeout expects a callback method as a first parameter and that's what is getting passed when you call setTimeout(tester,2000);.

Essentially, you are referring to method definition when you just specify name. However tester() is method call.

see the below style of defining method. That's way it's clearer that tester is actually method definition:

var tester = function(){

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download