arrow_left_alt Back to Blog

2Minutes: Function Hoisting In JavaScript

calendar_today July 13, 2026 | timer 2 min read |

What is Function Hoisting in JavaScript ?


We see everyday something similar to this in JavaScript scripts:

let counter = countdown(10);

counter(); // counter value is 10

// Some code goes here

function countdown(from) {
  let counter = from;
  return () => counter--;
}

If you look closely, you see that we’ve used countdown() function even before defining it, and it does worked and everything goes well without any errors. Why is that ?

This behavior is called hoisting. It occurs when a function is called before its declaration appears in the source code. JavaScript hoists function declarations to the top of their scope during the creation phase of execution, making them available to call before they are defined in the file. Just imagine it as a pre-step where JavaScript interpreter moves all function declarations to the top of their scopre before executing the code.

Note that this behavior applies to function declarations, not function expressions or arrow functions assigned to let or const.

let counter = countdown(10); // ReferenceError: Cannot access 'countdown' before initialization

counter(); // Never executes

const countdown = (from) => {
  let counter = from;
  return () => counter--;
};

Well here we have both countdown and counter varaibles hoisted, but yet not initialized that’s why the interpreter throws an error.

For var, we will get:

var counter = countdown(10); // TypeError: countdown is not a function

counter(); // Never Executes

var countdown = (from) => {
  let counter = from;
  return () => counter--;
};

All of var, const, and let throw an error here, but different ones. Why different? That’s something we’ll learn in another article about variable hoisting.

The takeaway for today is that function declarations get hoisted and can be used before they are defined, while function expressions cannot.

That’s 2Minutes Concept, see you in the next one where I will explain variable hoisting !

Sources


https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

https://www.geeksforgeeks.org/javascript/javascript-hoisting

https://www.freecodecamp.org/news/what-is-hoisting-in-javascript-3

index.php