Var vs. let in js

Gal Ilinetsky
CodeX
Published in
3 min readNov 7, 2022
Photo by Tengyart on Unsplash

let was first introduced in ES6(2015).

In this article, I would like to go over the differences between var and let in javascript.

Hoisting

Hoisting is JavaScript’s default behavior of moving declarations to the top.

In order to understand the following example we need to know that in JavaScript, a ReferenceError is thrown when trying to access a previously undeclared variable. On the other hand, if a variable is declared and not assigned any value it’s undefined

When we try to access variable x the ReferenceError is not thrown, because hoisting is allowed with var and therefore variable x is declared but not assigned.

Hoisting is not allowed on let variables therefore ReferenceError is thrown.

Function scope vs Block scope

The difference between both scope types is the accessibility of a variable declared within the scope.

In function scope, the declared variable is accessible within the function in which it is declared, and within any functions nested within that function. The variables that are defined with var keyword have function scope.

from chrome

As you can see in the example the variable d is accessible in the nested function nestedFunc as it was declared in the primary function f. The variable r is accessible out of the if-statement because it is used under the same function it was declared at.

when it comes to block scope each block of code within curly braces has its own scope, and variables are not accessible outside of the block in which they are declared. The variables that are defined with let keywords have block scope.

Therefore if we will change the variable r definition to be let we will fail:

Declaration

Redeclaring a variable using the let is not allowed, a SyntaxError will be thrown.

Redeclaring a variable using the var is allowed, but is a bad practice, it is very confusing, as you can see in the following example:

So if you are a C# developer, for example, the use of let might be more familiar to you in JavaScript, and much safer in some cases as it prevents confusion.

--

--

Gal Ilinetsky
CodeX
Writer for

Software Engineer, .net development focus. Here to share my knowledge on points of view on software development fields I take interest in.