Basic Concept of Hoisting in Native Javascript

Posted By : Anchal Gaur | 31-May-2019

In programming language when javascript complies all of the code the variables which are declared using var keyword are hoisted to the top of their functional/local scope(if declared inside the function) or top of their global scope(if declared outside of the function) regardless of the actual declaration.

Lets some basic example to understand the concept of hoisting.

console.log(myName);
var myName = ‘John’;

It will get the following output.

1. Uncaught ReferenceError: myName is not defined.

2. John

3. Undefined.

It turns out that the third one is the actual answer.

As we have discussed earlier in the code when javascript compiles all of the code variable get moved to the top of their scope. Here the important thing is that only the variable declarations are declared at the top not the actual value given to the variable.

For more clarifications, If I have a chunk of code and lets say that on line 9, we have 

var name = 'Smith'

In this case when the Javascript gets compiled var name moved to the top of its scope while name='smith' would stay at the same line.

Lets look the same code and check how it behaves at run time.

var myName;
console.log(myName);
myName = John;

so that is why console.log is able to give the output 'undefined' becuase it identifies that the var myName is defined but the variable does not give any value till the third line.

we have also mentioned that the functions are hoisted to the top.

So if we look at the following exmaple.

function test() {
console.log('test ' + name);
};
test();
var name = 'John';

In this exmaple, the test function will still return undefined becuase javascript interpreter compiles the code at run time.

function test() {
console.log('test ' + name);
};
var name;
test();
var name = 'Smith';

So by the time the functions gets called there is a variable called myName exist but does not having any value

 

Are you interested in getting your mobile or web apps developed using native JavaScript contact us today! 

About Author

Author Image
Anchal Gaur

Anchal has a good knowledge of HTML,CSS and Javascript. She is working here as a UI Developer. Her hobbies are travelling and to read novels in free time.

Request for Proposal

Name is required

Comment is required

Sending message..