The variables are declared using var are created before any code is executed and assigned with an initial value of undefined. This process is called hosting.
The scope of the variable declared with var will be inside the current execution context and closures. That may be either the enclosing function and function declared within it or variables declared outside any function globally. Duplication of the variable name using var will not throw an error, even in strict mode and the variable will also not lose its value unless another assignment is performed.
var name = "Abc";
function logName() {
console.log('1. Name is => ', name); // Abc
var name = "Grapes";
console.log('2. Name is => ', name); // Grapes
}
logName();
The variable name is bounded with globalThis where as variable name inside the function logName() is bounded with the logName function.
var name = "Abc";
globalThis.hasOwnProperty("name") // true
All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var declarations are initialized with undefined, but let and const declarations remain uninitialized.
The variable declared using const or let they will only get initialized when their lexical binding (assignment) is evaluated during runtime by the JavaScript engine. This means you can’t access the variable before the engine evaluates its value at the place it was declared in the source code. This is what we call “Temporal Dead Zone”, A time span between variable creation and its initialization where they can’t be accessed.
If the JavaScript engine still can’t find the value of let or const variables at the line where they were declared, it will assign them the value of undefined or return an error (in case of const).
console.log(name); // ReferenceError: a is not defined
let name;
console.log(name); //undefined
name = "test";
console.log(name); //test
This is when the function logName is called the console.log(name) will get executed and it looks up for the variable name inside the local execution context. when it is not found inside the local execution context it goes outside and looks for the variable name and it will be inside the globalThis so it prints Abc when the variable is declared using var and not when declared using const or let.