DEV Community

loading...

A Quick Look At Hoisting in JavaScript

davidbell_space profile image David Bell Originally published at davidbell.space ・1 min read

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

Discussion

pic
Editor guide
Collapse
jarek profile image
Jarosław Księżuk

There is a difference between a function declaration and a function expression.

Functions defined using an expression are not hoisted.

You can read more here: w3schools.com/js/js_function_defin...

Check all of types and try to understand it correctly ;-)

function test() {}

const test = function() {}

const test = () => {}

(function () {
var test = 1;
})();

Collapse
asifurrahamanofficial profile image
Asifur Rahaman

Thanks 😊