Hoisting in JavaScript

Michael Abe
3 min readDec 23, 2021

--

An important aspect of coding in JavaScript is making sure that we are always aware of the scope that we are dealing with. Scope is essentially the reach that something has. In most traditional coding situations there will be a local scope and global scope but JavaScript also has something called ‘block scope’. Local and global are fairly straight forward. Global scope is pretty easy to understand, it is a declaration that applies globally or everywhere. Local scope is essentially within a function. A variable declared within a function locally will exist only in that function. A great example of this is when we write a loop and use ‘i’ as a counter. If these became a global scope variable, we would basically have to use a new variable as the counter for every loop that we made. Even smaller than the local scope in JS is the block scope. By using ‘let’ and ‘const’ to declare variables within a block (indicated by use of ‘{}’ curly braces) the variable exists only within that actual block.

Now that we have touched a bit on scope in JavaScript, let’s have a look a the concept of hoisting. By default JavaScript wants to move all declarations to the top so that the variables that are set can all be read. Essentially what was taught to me is that JavaScript is a ‘read twice’ language. The idea is that upon first read, JS hoists the deceleration's to the top of the current scope so that you there won’t be issues running something out of order since the existence of the declaration isn’t dependent on order at all.

In the example above we can see that even though we don’t declare ‘y’ as a variable until after we set it’s value, we are still able to log it to the console because the declaration was hoisted.

Here we have the exact same code except for line ‘4’. Instead of using ‘var’ to declare our ‘y’ variable, we are using ‘let’. The reason that this does not work is because ‘let’ and ‘ const’, while they are hoisted to the top of the block, they are not initialized. Ultimately what is happening here is that the block of code while aware of the variable, is unable to use the variable until it is declared.

While this may seem confusing at first, the best advice that I ever received was to always declare variables at the beginning or top of every scope. This simple idea will help keep things tidy and working (not to mention much easier for others to read). A little bit of organization can go a long way towards concise functional code.

--

--