The Difference Between Var, Let, and Const in Javascript

A common interview question explained

This question seems to come up in almost all of my interviews and rightfully so because it is one of the basic concepts in javascript programming and is used almost every time you start coding in javascript.

You use let, var, and const in javascript to declare variables. Before ES6, it was only possible to use var. Now, there is more functionality and flexibility when using these declarations and assigning a variable.

If var is used within in a function, then it is only available within the that function. If it is not used within a function it is a global variable and will be recognized anywhere within your code. Var is also hoisted which means that it does not matter where you define that variable within your code on the global scope it will still be recognized and available for use in code before your actual declaration. With var as well, you can declare it and not actually assign it a value, unless you want to later. Using var in the global scope will bind it to the “this” keyword, referring to the window object.

function printCoins(){
printCoins()var numberOfCoins;numberOfCoins = 5

In the example above. We are executing printCoins() but numberOfCoins is declared and then assigned a value AFTER the execution. In this case printCoins() will still print, “5”.

Let and const were introduced in ES6, because with var, there are too many instances that are prone to error. Var can be easily reassigned a value anywhere within your code and became increasingly difficult to debug. Let solves this by only having the variable available within the block of code within which it is defined. Let is not hoisted and you must assign it a value upon its declaration.

Const is similar to let. The only difference is you cannot reassign any variable declared with const. This assures that you are not accidentally reassigning its value if it is a variable that you want to remain constant throughout your program. However, you may edit and built upon variables declared with const, such as when you are manipulating an array with .push() or .shift() or inserting key-values within an object.

const numberArray = [1, 2, 3, 4, 5]const numberArray = [5, 4, 3, 2, 1]

Above, this will not work. It will throw and error. However :

const numberArray = [1, 2, 3, 4, 5]numberArray.push(numberArray[4] + 1)console.log(numberArray)
numberArray = [1, 2, 3, 4, 5, 6]

Being able to explain the differences between these 3 variables declarations in a javascript interview is essential for passing it. I’ve had this question asked in almost every tech interview I have had so far. I hope this post helps in the understanding of var, let, and const a little bit better.