Function hoisting lets you use functions before you write them in your code. This helps organize code in a flexible way.
Function hoisting behavior in 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.
sayHello(); function sayHello() { console.log('Hello!'); }
sayHi(); // TypeError: sayHi is not a function var sayHi = function() { console.log('Hi!'); };
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.
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();
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.
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.