Consider this JS (which is run at the end of the body and causing an error)
(function(){
"use strict";
var div = document.getElementById("hook"),
ul = div.firstElementChild,
last_li = ul.lastElementChild;
alert(div) // alerts "Uncaught TypeError: Cannot read property 'children' of undefined"
})();
I then removed the commas and added the var keyword, but received a similar error (it's not the HTML):
(function(){
"use strict";
var div = document.getElementById("hook");
var ul = div.firstElementChild;
var last_li = ul.lastElementChild;
alert(div) // alerts "Uncaught TypeError: Cannot read property 'lastElementChild' of undefined "
})();
The only way it works is by adding the alert() statement directly after the div assignment. I'm assuming this has relevance to variable hoisting but am not experienced enough to know for sure.
Can someone give a quick synopsis of variable hoisting and what may be going on here? Thanks!