Sobes.tech
Middle

Why can a regular function be called before its declaration, but not an arrow function?

sobes.tech AI

Answer from AI

Regular functions in JavaScript are created using Function Declarations, which are hoisted to memory during the compilation phase. This means they can be called before their actual declaration in the code because the interpreter already knows about the function's existence.

Arrow functions are most often created as Function Expressions, for example, assigned to a variable. Such variables are hoisted but not initialized, so before the declaration line, they are undefined. Attempting to call an arrow function before its declaration will result in an error.

Example:

// Can be called before declaration
console.log(sum(2, 3)); // 5

function sum(a, b) {
  return a + b;
}

// Cannot be called before declaration
console.log(multiply(2, 3)); // Error: multiply is not a function

const multiply = (a, b) => a * b;

Thus, the difference is related to the hoisting mechanism and the type of function declaration.

Why can a regular function be called before its… - sobes.tech