Difference of calling a function with and without parentheses in JavaScript

With parentheses the method is invoked because of the parentheses, and the result of that invocation will be stored in before_add.

Without the parentheses you store a reference (or “pointer” if you will) to the function in the variable. That way it will be invoked whenever someone invokes before_add().

If that didn’t clear things up, maybe this will help:

function Foo() {
    return 'Cool!';
}

function Bar(arg) {
    console.log(arg);
}

// Store the >>result of the invocation of the Foo function<< into X
var x = Foo();
console.log(x);

// Store >>a reference to the Bar function<< in y
var y = Bar;
// Invoke the referenced method
y('Woah!');

// Also, show what y is:
console.log(y);

// Now, try Bar **with** parentheses:
var z = Bar('Whut?');

// By now, 'Whut?' as already been output to the console; the below line will
// return undefined because the invocation of Bar() didn't return anything.
console.log(z);

If you then take a look at your browsers’ console window you should see:

Cool!
Woah!
function Bar(arg)
Whut?
undefined

Line 1 is the result of invoking Foo(),
Line 2 is the result of invoking Bar() “via” y,
Line 3 is the “contents” of y,
Line 4 is the result of the var z = Bar('Whut?'); line; the Bar function is invoked,
Line 5 shows that invoking Bar() and assigning the result to z didn’t return anything (thus: undefined).

Leave a Comment