1

I've noticed that you can reference a function with or without the parentheses. Why?, what's the difference?

As a slight aside, I've noticed this works: window.onload = functionName;

Whereas this doesn't: window.onload = functionName();

Could anyone explain why the top line of code works and the bottom doesn't?

0

5 Answers 5

9

The () version doesn't reference the function. It invokes the function and references its return value.

Given this function:

function functionName() {
    return "I'm a function";
}

This references the function:

 // window.onload will reference the function, and invoked it when the page loads
window.onload = functionName;

...but this references the string that was returned, which isn't very useful to window.onload:

 // the function is invoked immediately, so now window.onload references the
 //    string "I'm a function" that was returned
window.onload = functionName();
Sign up to request clarification or add additional context in comments.

Comments

2

Writing func() calls the function and evaluates to its value.

Writing func just evaluates to the function itself, without calling it.
(Just like writing myVar evaluates to its value)

Comments

1

In JavaScript, functions are first class members which means they can be treated much like other data types in language. For example, you can assign a function to a variable, pass it as an argument, return it from function etc.

Given this, functionName simply refers to the function object while functionName() invokes the function that is referenced by functionName.


This assigns the function refered to by functionName (which doesn't even have to be the actual function name, it could be a variable that was assigned to the function - an alias as it were! For example, var functionName = myOtherFunction; - this creates an alias for myOtherFunction)

window.onload = functionName;

while this invokes the function referenced by functionName and assigns it's result

window.onload = functionName();

Comments

0

functionName() calls the function, then and there. On the other hand, x = functionName assigns the function 'functionName' to x. From that point onwards, calling x() is similar to calling functionName(). In the case of window.onload, your browser will call window.onload() when the page loads.

Comments

0

functionName is a name of variable holding reference to a function. functionName() is an invocation of the function in that variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.