0

Why do functions nested in an anonymous function wait for button click (as it should), but when the function is not nested it runs on page load without waiting for button click?

Working example:

btn1.onclick = function() {cityChoice(1)};
     //code works only on button click as expected

Not working example:

btn1.onclick = cityChoice(1);
     //function runs on pageload without waiting for button click?

Any links to documentation/articles are welcome, as I could not find them on Google nor on StackOverflow that explained this.

Coding language: JavaScript (vanilla)
Skill level: Beginner
Editor: Visual Studio Code
OS: Windows 7

  • In the second example you are not assigning a function to `btn1.onclick`; you are calling `cityChoice` with the arg `1` and returning the result which you are assigning to `btn1.onclick`. – Alexander Nied Apr 21 '22 at 17:20
  • 2
    Does this answer your question? [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) – Ivar Apr 21 '22 at 17:24

4 Answers4

0

btn1.onclick = cityChoice(1); isn't a nested function. You merely called the cityChoice function and its return value saved as onclick property of variable btn1.

There are several ways you can achieve the same thing to bind listener to an event:

btn1.onclick = function() { } <-- anonymous function

btn1.onclick = () => { } <-- arrow function


In conclusion:

btn1.onclick = cityChoice(1) <-- cityChoice function is invoked and its value is saved to btn1.onclick

Ref:

Anonymous functions in JS

Arrow functions in JS

BrunoT
  • 414
  • 4
  • 9
0

cityChoice is a function and I assume you're trying to pass it your default argument 1 the problem you're seeing is that you're invoking cityChoice in your second example and assigning the result of cityChoice(1) to onclick instead of registering an event handler. This I assume would return a normal javascript object. onclick needs to be an event handler (any function anonymous or not)

Brandon Piña
  • 614
  • 1
  • 6
  • 20
0

When you use this cityChoice(1); without nested function.

Javascript understand it like you type it without onclick event It's like you call it on page load.

But function statment assign new function when called it call cityChoice(1).

Philo
  • 428
  • 4
  • 11
0

All the event handlers (like onClick) expects a Function reference (1st option) and not the Function result (2nd option). Here is the official document from MDN which explains it nicely.

When the event (for example, click) is triggered, it executes the Function you're passing to it. So if you pass a return value from a Function to onClick event, it won't be able to execute it, and you would get an error.

I hope this explains the concept in simple terms.

Anindya Dey
  • 825
  • 1
  • 8
  • 18