Javascript var, let and const

Tpatel
Nov 18, 2020

This will be a quick reference to the differences of var, let and const. I’ll get straight to the point :)!

Var

With the introduction of let and const in the 2015 update to ES6 the var declaration was made more obsolete. Var has the ability to be redeclared and updated. It is globally scoped when declared outside a function and function scoped when inside a function.

The problem with var is that when you declare and initialize a variable with var, it can then be redeclared and changed. Where you did not knowingly want this to happen. In a larger code base you may have accidentally declared with var twice using the same name. This can cause bugs if this was not the intention.

Let

With Let the above problem was solved. Let is block scoped, and cannot be redeclared within the same scope. It can be updated, however. If a let variable is declared at the top of a program and updated inside a block and not redeclared that variable will change in the rest of the program if the block is called upon(if a function being called or a conditional statement passes true).

If you redeclare the variable in a different block it will only have that value in that block since it is like creating a new variable.

Const

And finally with const declarations you cannot update or redeclare the variable in the same block. These must also be initialized to a value at time of declaration.

--

--