Let vs var in JavaScript

With ES6, two new keywords, let and const, were introduced for declaring variables. Until then the only available keyword was var. Const as the name implies can not be changed for primitive values, however, we can change the properties of constant objects.

The focus of this post is on var and let which differ in three ways:

1. Hoisting

If you try to access a variable before it is defined, variables defined with var return undefined while those with defined return a ReferenceError. The reason for this is variables defined with var are hoisted to the top but that's not the case with let. Hoisting in simple terms means JavaScript moves all declarations to the top of the current scope but the values don't get assigned until JavaScript reaches that point in code.

2. Scope

A variable defined outside of a function or block is a global variable as it can be accessed anywhere in the current document. A  variable defined within a function has a local or function scope as it can not be accessed from outside that function. With ES6 the variables can be scoped to the nearest pari of curly braces and, therefore, can not be accessed from outside.

As can be seen from the code above, let variables are both function and block scoped and can not be accessed from outside their respective scopes. Var on the other hand is only function scoped and can be accessed from outside the block.

3. Redeclaration

Variables defined with let or var can be reassigned which makes perfect sense. However, when we try to declare a variable that has already been declared, both exhibit different behaviour.

With let, a variable can only be declared once, so if you or someone from your team tries to redeclare it, you will get a reference error. With var, the variable gets overwritten and this increases the risk of overwriting useful data and can break your code.

Have a project in mind?
Let's discuss

Schedule a call