A Quick Look At Hoisting in JavaScript

davidbell_xyz

David Bell

Posted on October 21, 2020

A Quick Look At Hoisting in JavaScript

Hoisting is a tricky one. Here is the most basic explanation I can possibly think of for it.

Explained

Essentially allows you to use functions and variables before they have been created.

When JavaScript is first read the JavaScript compiler takes all of your functions and put’s them to the top. So you can technically use a function before it exists.

Example 1

hoisty()

function hoisty() {
  console.log("hoisted!!!")
}
// hoisted!!!
Enter fullscreen mode Exit fullscreen mode

The function hoisty() is declared at the top of our file. Above the declaration. Due to hoisting however the function hoisty() is taken to the top of the file when it gets compiled.

Example 2

hoisty()

function hoisty() {
  console.log(addNums(3, 7))
}
// 10
function addNums(a, b) {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

In this example we declared the function addNums() at the bottom of our file. Yet the function hoisty() still passed 3, 7 into addNums() with the answer 10 being logged to the console.

Note

Hoisting only works on functions with the function key word function hoisty() not with arrow syntax const hoisty = () =>.

Let's connect

Twitter

💖 💪 🙅 🚩
davidbell_xyz
David Bell

Posted on October 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related