Before Understanding the difference b/w let and var. First understand the Scopes in JS.
Scopes - where to look the variables in the memory.
Note : Here companyName becomes accidental global and bind with window object .
Scope is A compile time process.
Var Hoisting in js
When JS Compiles all of your code, all variables using
var are lifted to the top of their scope, either on
Functional scope or global scope. This is called Hoisting.
console.log(‘My Name is ‘,myName);
var myName = ‘Brain Mentors’;
myName goes under window object.
Functions are also hoisted at the top.
- Block Level Scope.
- Redeclaration the same variable in same function/block generates SyntaxError.
- TDZ (Temporal Dead Zone)
- Different let in different scope, but var use the same one.
Let is not global
Outside the loop if u try to access the i variable. i is under block level scope.
if you try with var
Note : let not use Lexical scope principle.
Temporal dead zone - TDZ
That's all Folks , See u in a next blog , Happy Learning 😎