JavaScript running order question

Hi everybody. This is my first post, so I apologize if there are any mistakes.

While learning JavaScript in the topic “What is JavaScript?”, “JavaScript running order”, the question arose:

You need to be careful that the objects referenced in your code exist before you try to do stuff to them.

Everything is clear with this, but in the above example, the updateName function is used earlier than it was created (below in the code):

I’m just at the beginning of my JavaScript learning and don’t want to misunderstand the basics.
I suspect that this is a feature of the function or .addEventListener, but I’m not sure. Can someone please explain this for me in detail?

Hi @Ti_awer, and welcome to the community.

This is a really good question, and has to do with how JS code is parsed by the browser. It is fair to say that generally it runs instructions from top to bottom, in order, but this is not always true of everything.

In the case of functions defined using the function keyword (also know as a function declaration: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function), the browser looks through the entire code, and “hoists” the functions to the top so they are are available to all the code.

This stack overflow post is also helpful here: https://stackoverflow.com/questions/2742195/javascript-parse-evaluation-order

Thank you very much for the detailed answer and helpful links. I just don’t know if this point will be explained further in the lessons (I think yes, but nevertheless), and it will eat me.
Thanks again and have a nice day.

I don’t think I’ve actually explained this anywhere in the lessons, so I probably need to add a bit somewhere :wink: