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
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:
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)
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).