JS Concepts: Hoisting

Danilo Peña
3 min readAug 4, 2021
Photo by mirsad mujanovic from Pexels

There are many concepts you must understand when you are programming with Javascript. One of them is Hoisting.

The hoisting in Javascript is just a behavior. The name we use to describe a simple but important occurrence in Javascript: the variable and function declarations are always first.

Let’s start with an example:

What is happening? Let’s going to take a look line by line:

  • first line: helloWorld = "Hello Medium" here we are assigning a value to our variable.
  • second line: console.log(helloWorld) here we are passing the variable’s value to the log function. It will print our value: Hello Medium
  • third line: var helloWorld here we are declaring a variable called helloWorld

This code may looks messy, because we are assigning a value to a variable that has not been declared yet and we are printing in console that variable’s value. In spite of that, this is correct and the compiler will be print our value in the console without errors.

Why?

Because of the hoisting.

Basically, the compiler will allocate memory for all of our functions and variable declarations before the code execution.

As you can see in the comments of our code, this is what the compiler does: Put our variable declaration first, allocating memory for the variable declaration, then runs the rest of the code!

Let’s see other examples:

Same happens with functions. As you can see in the example:

  • first: helloWorldFn() We are calling the function helloWorldFN()
  • second: function HelloworldFn() .... We are declaring a function helloWorldFn() that prints a simple Hello Wolrd string.

This will run normally without errors. Because in compile time the compiler will put the function declaration at the top of their scope.

Heads up: Only the declaration is hoisted.

Note that if you try to print a variable before a value assignment, this will throw an undefined . The compiler only puts the variable definition at the top of the scope.

Hoisting with Let and Const

Variable declaration with let and const is different than var .

Unlike var declarations, when you declare a variable with let , that will not be initialized with an undefined by default. So the compiler will throw a ReferenceError

With the const keyword, you have to initialize the variable when you declare it. So if you try to do the same exercise, the compiler will throw you a SyntaxError .

Conclusions

Hoisting is not a kind of normative but is very useful to understand the way our compiler works in the execution of our Javascript code!

Complete this knowledge with the Javascript’s Scope and the difference between var , let and const .

--

--