Let's understand the how DOM parsing works on Browser.
When we load any document/HTML on DOM/Browser, It starts document parsing. It iterated elements and creates a DOM tree. It starts from TOP, goes to the header and check for other resources and execute them one by one.
Here when you wrote
let div = document.getElementById('display');
in simple script tag without wrapping it into any function, it executed first without getting your DOM loaded.
Which means, the parser is looking for DIV by its ID which is not present yet on the browser. Hence it is undefined. Now the question is how does it work inside the function?
Functions in JavaScripts gets executed on DOMContentLoaded
. This is similar to jQuery ready()
. This ensures that the DOM has been ready and each element on the browser has been traversed and is now in DOM tree.
Now, you probably thinking how it works when we put this code at the bottom of the page? like
<html>
<head></head>
<body>
YOUR HTML
</body>
<script type="text/javascript">
//YOUR JS CODE
</script>
So when we insert JS which is looking for an element in DOM at the top of the page in head tag and if there is an error in getting the JS executed (like in your case the JS is looking for DIV which is not on DOM yet) it will stop the execution of DOM unless the script resolved the error.
Hence when we place JS code at the bottom of the page, the browser has already parsed all the page element and the DOM tree is ready. Thus, any element is now accessible by JS.
Which means, if you write your above code at the bottom of the page, it will get the element without error.
Footnote:
Read more about how JavaScript works on browser
https://javascript.info/onload-ondomcontentloaded
Where should I put <script> tags in HTML markup?
Hope this helps,
Thanks
-AG