Calling functions - question

I am practicing with running functions and have a question about the syntax. When I run this on a webpage, the alert box will pop up when you mouse over whatever element has the id pic.

VERSION 1:
let myVariable = document.getElementById(‘pic’);

myFunction = () => {alert(‘hey’);}

myVariable.onmouseover = myFunction;

VERSION 2:
let myVariable = document.getElementById(‘pic’);

myFunction = () => {alert(‘hey’);}

myVariable.onmouseover = myFunction();

When you run the 2nd version, the alert box comes up immediately and does not require mouseover action. Could someone explain the reason for this? What’s the significance of the parenthesis?

1 Like

Hey @fina201,

That is a very good question! I’ll try to explain :wink: . @mtf correct me if I am wrong.

This has to do with how Javascript works.
In both versions whilst doing myVariable.onmouseover = you are doing an assignment similar to lets say let fish = shark. But the difference in the two versions lies in what you assign to myVariable.onmouseover.

In any assignment the code is executed immediately upon calling. For example if you say let sum = 1 + 2 the operation 1 + 2 is executed and stored in the variable sum. If you then reassign it to 2 + 4 the same happens again, executed and stored.

Now back to your question.

In version 1 you assign myFunction as a reference to myVariable.onmouseover.

Any function in javascript is actually an object. In this case {alert(‘hey’);}. The moment you call the variable myVariable.onmouseover the browser looks at this object, finds the alert and executes it.

However in version 2 you are assigning a function call myFunction().

A function call executes what is inside the function object and returns what the function presents as a return. Thus, upon assignment the function is executed and it stores the return value to your myVariable.onmouseover. To test this, if you do console.log(myVariable.onmouseover) it should print undefined.

Thats why your alert pops up immediately.

I hope I explained this to you in a way you understand / can grasp it.

Happy coding!

2 Likes

Got it. Thank you! :grin: :call_me_hand:

2 Likes

Global event listeners are methods that all objects inherit from Object.prototype, that’s why we can attach them to any newly created object such as a DOM node. All listener methods are Higher Order Functions, meaning they take a function as their argument. This function is known as a callback.

In your example you have written the callback as a standalone function, and assigned the reference to the listener method attached to your selected node. As mentioned, we do not want the callback to be invoked unless an event triggers it, hence the invocation () is left off.

1 Like

What’s more, we are not really assigning a value as much as passing an argument since that is what the method expects. The interpreter is taking care of the details. We are merely declaring this as the event handler.

1 Like