0

Assigning event handler like so:

document.addEventListener("DOMContentLoaded", myFunction);

is it required for the handler function to be defined before the assignment code? In other words if the codes below

function myFunction() {...}
...
document.addEventListener("DOMContentLoaded", myFunction);

and

document.addEventListener("DOMContentLoaded", myFunction);
...
function myFunction() {...}

are identical?

Mulligun81
  • 119
  • 1
  • 13

1 Answers1

2

...are identical?

They are if you use the form you've shown, which is a function declaration. Function declarations are processed before any step-by-step code in the scope. If you used a function expression instead (var myFunction = function() { ... };), it would have to be before the addEventListener call. More about the difference in this question's answers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875