Function Hoisting

In many programming languages, such as Python, a function must be defined linearly in the file before it can be used. If you try to call a function before defining it, the compiler will throw an error.

JavaScript behaves differently due to a concept called hoisting.

How Hoisting Works

As long as a standard function is declared somewhere in the file, it can be called even before its definition appears in the code.

// Calling the function before it is defined
console.log(getLabel(3)); // Output: 'awful'

// The function definition
function getLabel(numStars) {
  if (numStars > 7) {
    return "great";
  } else if (numStars > 3) {
    return "okay";
  } else {
    return "awful";
  }
}

This works because the JavaScript engine parses the file in two passes. During the initial pass, it finds all function declarations and “hoists” them into memory at the top of their scope before actually executing the code line by line.

Note: This specific hoisting behavior applies to functions declared with the function keyword. If you assign a function to a variable declared with let or const (e.g., an arrow function), it will not be hoisted in the same way.