0
0
Javascriptprogramming~5 mins

Function hoisting behavior in Javascript

Choose your learning style9 modes available
Introduction

Function hoisting lets you use functions before you write them in your code. This helps organize code in a flexible way.

You want to call a function at the top of your script before its actual code appears.
You want to organize helper functions at the bottom but still use them above.
You want to understand why some functions work even if called early in the code.
Syntax
Javascript
function functionName(parameters) {
  // function body
}

Function declarations are hoisted completely, so you can call them before they appear.

Function expressions (like assigning a function to a variable) are not hoisted the same way.

Examples
This works because the function declaration is hoisted.
Javascript
sayHello();

function sayHello() {
  console.log('Hello!');
}
This causes an error because the variable is hoisted but not the function assignment.
Javascript
sayHi(); // TypeError: sayHi is not a function

var sayHi = function() {
  console.log('Hi!');
};
Sample Program

This program shows that the function declaration greet can be called before it is written because of hoisting. But calling the function expression sayBye before assignment causes an error.

Javascript
greet();

function greet() {
  console.log('Good morning!');
}

// Calling a function expression before assignment
try {
  sayBye();
} catch(e) {
  console.log('Error:', e.message);
}

var sayBye = function() {
  console.log('Goodbye!');
};

sayBye();
OutputSuccess
Important Notes

Function declarations are fully hoisted with their body.

Variables declared with var are hoisted but initialized as undefined until assignment.

Function expressions behave like variables and are not hoisted with their function body.

Summary

Function declarations can be called before they appear in code because of hoisting.

Function expressions cannot be called before assignment.

Understanding hoisting helps avoid errors and organize code better.