Ask coding questions

← Back to all posts
Let and Var
WilliamXing (43)

What is the difference between Let and Var? Please say it in an understandable way, not something you copied from the internet.

Baconman321 (1058)

let and var declare variables in different ways.
You can't hoist variables when declaring with let (you can't use them before they are declared), but you can do that with var. Also, let and var are scoped differently. If you have used functions before, you have gone into a different "scope". Scope refers to the accessibility of variables and other information stored.

It's a bit confusing to me too, but let is refrained to the code block it is in, while var is refrained to the function it is defined in. An example is that you can't use variables declared with let outside of the object it is defined in while var can be used anywhere inside the current function it is in (think difference between functions and objects).

Another difference is that you can re-declare variables declared with var, but not with let.

var foo = "bar";
var foo = "baz";
//This is ok.


let foo = "bar";
let foo = "baz";
//This will throw a syntax error!

Read more:

Coder100 (16841)

The easiest way to describe it is to try out these code:


var a = 5;

let a = 5;

As you can see, var actually hoists it:

var a;

a = 5;

while let, later added to fix this bug is more intuitive, and would throw an error instead.

Always use let unless u boomer

btw for var, you can use blocks too:

(function () {
  var a = 5;




let is limited, while var is global. Meaning, var has no limit, it can be used anywhere, while let is limited.

WilliamXing (43)

Why do we use let than?

19wintersp (1121)

@WilliamXing let is different to var in that it does not create a property on the global object (window in a browser) when used in global scope. It also respects scope, unlike var which is scoped to the function. This can help prevent pollution.


@WilliamXing meaning like, you can't use them as far as var

EpicGamer007 (1606)

Simply speaking. let is like the "new" version of var. The big difference is how they are scoped, let is block scoped whereas var is function scoped.

This stackoverflow question will give you much more info. Specifically the first answer