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?

4
  • well.. did you try it for yourself...? What did you find...? Commented Sep 18, 2017 at 10:10
  • @SudhirBastakoti: Trying it can be useful, but only tells you whether it works on the JavaScript engine(s) where you tried it, as opposed to whether it's supposed to work. Commented Sep 18, 2017 at 10:10
  • function declaration is hoisted which means it is evaluated before any other code in current context.. Commented Sep 18, 2017 at 10:11
  • @T.J.Crowder got it Commented Sep 18, 2017 at 10:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.