DEV Community

Cover image for JavaScript - Hoisting (2)
Top
Top

Posted on • Updated on

 

JavaScript - Hoisting (2)

Function Hoisting

Today, I am going to explain about JavaScript Function Hoisting

Do you know there are Two ways to write a function?

  • function expression
var fn = function() {
    // do something...
}
Enter fullscreen mode Exit fullscreen mode

A function expression gets hoisted just like a normal variable

  • function declaration
function fn() {
    // do something...
}
Enter fullscreen mode Exit fullscreen mode

A function declaration gets hoisted in its entirety

  • Example
fnDeclaration(); // This works !
fnExpression();  // fnExpression is not a funtion

function fnDeclaration() {
  console.log("This works !")
}

var fnExpression = function() {
  console.log("This won't work !")
} 
Enter fullscreen mode Exit fullscreen mode

Thank you :)

Top comments (1)

Collapse
 
curiousdev profile image
CuriousDev

Thank you, this shows an important difference and also, that JavaScript is not always easy. You know, not "every function" (as you show) is just hoisted and available at the beginning.

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓