Why do not we use parentheses here?

I thought we should write turnButtonRed(), but why dont we use parentheses here?

Hi @dariyavolosh9 - it’s a quirk of JavaScript behaviour.

When we write element.onclick = turnButtonRed; what we are doing is assigning the function (turnButtonRed) to the onclick event of the element. So, when we click the button it’ll call the function.

If we wrote element.onclick = turnButtonRed(); what would happen is JavaScript would interpret turnButtonRed() as a function call. Your button would immediately be restyled, and the onclick event for the element would be undefined (as that’s the return value of the function).

If you want to see what the difference is, add the parentheses to the onclick line and watch what changes. :slight_smile:

2 Likes

“parameters” should be “parentheses”, but I can’t change the post now so… :stuck_out_tongue:

Edit: I can now change my original post, thanks to the mod badge. It finally makes a bit more sense.

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.