Javascript understand the difference between let vs var Easily

The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block which can be smaller than a function block.
Both are global if outside any block.

Shivam Gupta
2 min readSep 8, 2019
Understand — let/var scope

So variable declares within a function can be accessed anywhere in the function.

You cant access variable declared with var outside of function because var is just global to its function level not outside of the function

Understand function level scope of var

Also, variables declared with let are not accessible before they are declared in their enclosing block.

Important

  1. You can’t redeclare variable using let but using var you can redeclare the same variable
Using let can not redeclare the same variable

2. If var, let declare in Global scope :

3. Block-level (let) and Function-level(var) scope Example

Variable j cant access outside for loop Block

Thanks for reading please give a clap if you like this post and follow me for more articles.

--

--

Shivam Gupta
Shivam Gupta

Written by Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

Responses (1)