Mastering Function Hoisting in JavaScript: Declaration vs. Expression

Uncover the secrets of hoisting and learn how to write more predictable and maintainable code

Max N
3 min readMar 19, 2024

JavaScript has a unique feature called “hoisting,” which can sometimes lead to unexpected behavior, especially when working with functions. In this article, we’ll explore the differences between function declarations and function expressions and how they relate to hoisting.

Function Declarations

Function declarations are the traditional way of defining a function in JavaScript. They follow a specific syntax:

function myFunction() {
// function body
}

When the JavaScript engine encounters a function declaration, it hoists the entire function definition to the top of the current scope (either the global scope or the function scope) before executing any other code. This means that you can call a function before it is declared in your code, and it will still work as expected.

sayHello(); // Output: "Hello, World!"

function sayHello() {
console.log("Hello, World!");
}

However, it’s important to note that only the function declaration itself is hoisted, not the function assignments or expressions.

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet