Wednesday, February 19, 2025

JavaScript, function hoisting

Does function hoisting take place in JavaScript?


Yes, function hoisting does occur in JavaScript, but it behaves differently depending on how the function is declared.

1. Function Declarations (Hoisted)
When you define a function using the function declaration syntax, JavaScript hoists the entire function definition (including the function body) to the top of its scope. This means you can call the function before it's declared in the code.

Example:



foo(); // Works because the function declaration is hoisted

function foo() {
  console.log("Hello, world!");
}
Here, the foo function is hoisted, and it can be called before the declaration.

2. Function Expressions (Not Hoisted)
If a function is assigned to a variable (i.e., using a function expression), only the variable declaration is hoisted, not the function itself. The function will be available only after the assignment in the code.

Example:



bar(); // Error: Cannot call a function before initialization

var bar = function() {
  console.log("Hello, world!");
};
In this case, the declaration var bar is hoisted, but the function is not assigned to bar until the line of code where it is defined. Therefore, trying to call bar() before the assignment results in an error.

3. Arrow Functions (Not Hoisted)
Arrow functions are also expressions, and like regular function expressions, they are not hoisted.

Example:



baz(); // Error: Cannot call a function before initialization

const baz = () => {
  console.log("Hello, world!");
};
Summary
Function declarations are hoisted entirely (both the function name and body).
Function expressions (including arrow functions) only hoist the variable declaration, not the function definition.

No comments:

Post a Comment

Hot Topics