JS Execution Context & Hoisting
So I was working on a couple problems and came across a strange thing with my code. If I invoke or log my variables & functions after declaring them, I get the expected results in the console below.
Hoisting is the answer. Functions and variables are moved to the top of their lexical scopes during execution context creation. What this means is that the JS interpreter runs thru your code and sets up memory space for them (var & function keywords are how the interpreter knows). Note that functions & their entire code are placed into the memory space. But variables have a 'undefined' placeholder for their assigned values. Also, if it’s a function expression instead of a function declaration, it will not be hoisted.
Even though this works in JS, it's bad practice to rely on hoisting. Better to call/invoke functions after writing their code.
To end today’s blog, I saw this on reddit a few days ago and made me laugh after a long day of hacking: