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.

But when I moved the 2 calls above the code, a strange thing happened. JS didn’t throw an error and returned an undefined value for the a variable and ran the b function. If Javascript runs the code line by line, how is it possible?

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:

Like what you read? Give Andrew Vedady a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.