Hoisted in JavaScript

Hoisted in JavaScript

In the JavaScript, the variables can be used before declared, this kinds of mechanism is called Hoisted. It's a default behavior of JavaScript.

You can easily understanding  in the below example in detail.

//The variable declaration look like.
var emp;

//The variable initialization look like.
emp = "Anil Singh";


var emp; //The declaration of emp is hoisted but the value of emp is  undefined.
emp = 10; //The Assignment still occurs where we intended (The value of emp is 10)

function getEmp() {
    var emp; //The declaration of a different variable name emp is hoisted but the value of emp is  undefined.

    console.log(emp); //The output is undefined
    emp = 20; //The assignment values is 20.
    console.log(emp); //The output is 20.
}

getEmp();

console.log(emp); //The variable named emp in the outer scope still contains 10.
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book