DEV Community

Ayush
Ayush

Posted on • Edited on

1

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).

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
arman_94 profile image
Mohammad Arman
Comment hidden by post author

Some comments have been hidden by the post's author - find out more

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay