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.