Before Understanding the difference b/w let and var. First understand the Scopes in JS.

Scopes - where to look the variables in the memory.

JS Scopes

Note : Here companyName becomes accidental global and bind with window object .

Scope is A compile time process.

Source : From MDN Docs
Source From : skillrisers.com

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.

Example:
console.log(‘My Name is ‘,myName);
var myName = ‘Brain Mentors’;
myName goes under window object.

Functions are also hoisted at the top.

Understanding Let

  • 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

Source : From StackOverflow

Example:

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

Source From SkillRisers.com
Source : From SkillRisers.com
Source : From SkillRisers.com
Source : From SkillRisers.com

That's all Folks , See u in a next blog , Happy Learning 😎