Hoisting with Example - Essential JavaScript Concepts

1 minute read

Hoisting is another important JavaScript concept. It defines that in JS every variable gets declared at the beginning of the function. It literally means as its name, which says raising something to top like hoisting a flag. It is JavaScript's default behavior of moving declarations to the top.

So basically Hoisting is a JavaScript concept where variables and function declarations are moved to the top of their scope before code execution. When JavaScript compiles our code, all variable declarations using var are hoisted/lifted to the top of their functional/local scope (if declared inside a function) or to the top of their global scope (if declared outside of a function) regardless of where the actual declaration has been made.

In core JS generally we should not declare and assign variable together at some point, it is considered as one the golden rules of JS. We should decide upfront our variables requirement for any function and declare them in the beginning itself. It means if we know Hoisting concept then before JS declare variables for us at the top, we should do it on our own in order to create bug free code.

Have a look into our video tutorial JavaScript Concepts: Hoisting Example | 0004-06, to understand Hoisting concept in simplest way. It also explains one practical example in detail from our GitHub repository https://github.com/rupeshtiwari/javascript-concepts. Snapshot of example with detailed description is shown below for better understanding. Same you can check out anytime from our GitHub code base.

Comments