In this tutorial, we will learn hoisting in javascript with example

Hositing:

  • Hoisting is a behavior in JavaScript where variables and function declarations are moved to the top of their scope before code execution.
  • In other words, even though a variable or function may be declared later in the code, it is treated as if it was declared at the top of its scope, making it accessible throughout the entire scope.

Examples:

console.log(x); // undefined
var x = 5;

Even though x is declared later in the code, it is still accessible at the top of the code because of hoisting. When this code is executed, the declaration of x is moved to the top of its scope and is assigned a value of undefined before its actual assignment to 5.

It’s important to note that hoisting only affects declarations and not assignments. Consider the following code:

console.log(x); // ReferenceError: x is not defined
x = 5;

In this case, the assignment of x to 5 is not hoisted, and attempting to access x before its assignment will result in a ReferenceError.

Example2:

add(1,3); // "John Doe"

function add(x,y) {
  console.log(x+y);
}

In this example, the function declaration add is hoisted to the top of its scope, making it accessible and callable throughout the entire scope. The function declaration is treated as if it was declared at the top of the scope, even though it is actually declared later in the code.

In general, it’s best to declare variables and functions at the top of their scope to avoid confusion and unintended behavior due to hoisting.

Thanks for Reading.