A Quick Look At Hoisting in JavaScript
David Bell
Posted on October 21, 2020
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!!!
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
}
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
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
October 25, 2024