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

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^