Hoisting in javascript

pappijx

Ayush

Posted on October 26, 2022

Hoisting in javascript

Image description

JavaScript Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

Hoisting allows functions to be safely used in code before they are declared.

Variable and class declarations are also hoisted, so they too can be referenced before they are declared. Note that doing so can lead to unexpected errors, and is not generally recommended.

Function hoisting

One of the advantages of hoisting is that it lets you use a function before you declare it in your code.

catName("Tiger"); 
function catName(name) { 
  console.log(`My cat's name is ${name}`); 
} /* The result of the code above is: "My cat's name is Tiger" */

Without hoisting you would have to write the same code like this:

function catName(name) { 
  console.log(`My cat's name is ${name}`); 
} catName("Tiger"); /* The result of the code above is the same: "My cat's name is Tiger" *
Enter fullscreen mode Exit fullscreen mode

Variable hoisting

Hoisting works with variables too, so you can use a variable in code before it is declared and/or initialized.

However, JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed, even if the variable was originally initialized then declared, or declared and initialized in the same line.

Until that point in the execution is reached the variable has its default initialization (undefined for a variable declared using var, otherwise uninitialized).

đź’– đź’Ş đź™… đźš©
pappijx
Ayush

Posted on October 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related