Difference between let and var in Javascript

Krish S Bhanushali
codeburst
Published in
3 min readJan 12, 2018

--

There has been a lot of confusion about the use of let and var in Javascript. So here is the difference where you would be now easily to decide what to use where and when.

Description

let gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var.

var is rather a keyword which defines a variable globally regardless of block scope.

Now, let me show you how they differ.

Global window object

Even if the let variable is defined as same as var variable globally, the let variable will not be added to the global window object.

See the example below -

var varVariable = “this is a var variable”;let letVariable = “this is a let variable”;

Say, here we have two variables declared. let us see what output it actually gives you.

console.log(window.varVariable); //this is a var variableconsole.log(window.letVariable); //undefined

Thus let variables cannot be accessed in the window object because they cannot be globally accessed.

Block

let variables are usually used when there is a limited use of those variables. Say, in for loops, while loops or inside the scope of if conditions etc. Basically, where ever the scope of the variable has to be limited.

For example: -

For loop using let variable: -

for(let i=0;i<10;i++){console.log(i); //i is visible thus is logged in the console as 0,1,2,....,9}
console.log(i); //throws an error as "i is not defined" because i is not visible

For loop using var variable: -

for(var i=0; i<10; i++){console.log(i); //i is visible thus is logged in the console as 0,1,2,....,9}
console.log(i); //i is visible here too. thus is logged as 10.

Thus, as you can see the var variable is logged as 10 outside of the for loop too.

--

--

Analytic problem solver by birth and programmer by choice. Motivator and spiritual. Portfolio: www.krishbhanushali.me