JavaScript Hoisting

JavaScript Hoisting

JavaScript hoisting is the concept in which all the declaration of variables goes on top of the script, file or function.

It’s the default behavior of JavaScript.

In JavaScript, it is possible to use a variable without its declaration. Its means that as in other languages like C++ we have to declare variable first and then use it or save some value in it For example:

Same in JavaScript var keyword is used to declare variables, but what hoisting says is that you can use a variable without its declaration.

Example:

The above code and the code below act same in output.

The difference between above two codes is in the first code we cannot declare the variable x. We just assign a value to x and show it in alert and in the nest code we first declare the variable x and then assign the value or initialize variable x with a value. This is because of javascript hoisting the declaration of the variable is going to top if it is but if it is not it automatically declare that variable in the start.

Variables Scope in JavaScript:

JavaScript scope is a bit different from the scope in other languages. You can understand this concept with the below example.

In JavaScript, the same example acts differently.

Declare variable at the end:

As in the example above the variable y is declare after it is used so due to JavaScript hoisting its deceleration goes on the top of the script.

Initializing is not hoisting:

“Initializing is not hoisting” means that initializing a variable and declaring a variable are two different things. Like

var ID;

the above line is declaring a variable ID.

ID=5; OR

var ID = 5;

The above line of code initializes a variable in the first line with value 5. In the second line, it declares and initializes at the same time.

Initializing means that assigning the initial value to the variable whereas declaring means reserving space in the memory for some variable.

So the concept is that if we declare a variable after its use, it will not affect the execution of the code and take the declaration of the variable automatically to the top of the script, but if we initialize a variable after its use, it will throw an error that the variable is undefined.

To understand it we use a simple code example:

But this code is slightly different from the below code in below code we try to initialize a variable after its use so it show us an error that the variable is undefined.

Initializing a variable after its use
Initializing a variable after its use