Hoisting in JavaScript

Introduction Link to heading

Hoisting is a fundamental behavior in JavaScript that affects how variables and functions are interpreted in code.

Hoisting with variables Link to heading

  • In older versions of JavaScript (before ECMAScript 6), variables declared with var are “hoistean” to the top of their scope (function or global).
  • This means that you can access a variable declared with var before its declaration line within the same scope.

Example Link to heading


console.log(myName); // Displays "undefined"

var myName; // It declares
myName = "John"; // It is initialized

// The variable can be accessed before its declaration

What’s actually happening? Link to heading

  • The JavaScript interpreter creates the variable as undefined at the start of the scope.
  • When the line console.log(myName) is executed, the current value of the variable is printed, which is undefined.
  • Subsequently, the value “John” is assigned to the variable myName.

Hoisting with functions Link to heading

  • Functions are also “elevated” at the beginning of the scope.
  • This means that you can call a function before its declaration within the same scope.

Example Link to heading

hey();

function hey() {
    console.log("Hello " + myName);
}

var myName = "John";

// The function can be called before its declaration

What’s actually happening? Link to heading

  • The hey() function is raised to the start of the scope.
  • When the line hey() is executed, the function is searched and executed.
  • The variable myName is not defined yet, so “Hello undefined” is printed.
  • Subsequently, the value “John” is assigned to the variable myName.

Important considerations: Link to heading

  • Hoisting can be useful in some cases, but it can also lead to errors and confusion if not understood correctly.
  • It is recommended to use let and const to declare variables instead of var, since these are not “elevated” and their scope is better defined.
  • Functions are always “raised” to the start of the scope, regardless of whether they are declared with var, let or const.

In summary Link to heading

  • Hoisting is a behavior that “hoists” variables and functions to the beginning of the scope.
  • It is important to understand how hoisting works to avoid errors and confusion in the code.
  • It is recommended to use let and const to declare variables instead of var.

Keep learning about hoisting to write cleaner and more efficient JavaScript code!

<< Scopes in JavaScript Coercion in JavaScript >>