Javascript – Difference Between var, let and const

ES6 introduced 2 new ways of declaring variables: let and const. There are a couple of main differences between these variable declaration methods and they still seem to confuse people. Let me very briefly explain the differences between var, let and const and give some examples.

Scoping with var, let and const:

let and const variables are block-scoped. var variables are function-scoped and subject to variable hoisting. A variable declared using let or const in a parent block can be reached from within sub-blocks and functions.

Assignment with var, let and const:

Variables declared using var and let can be re-assigned. Variables declared using const cannot be re-assigned. One thing to pay attention here is, objects declared using const can be modified/mutated, which is not the same as re-assigning. See the examples below.

To run the code:,console

Many developers seem to drift away from var declarations in favor of using let and const these days since most of the time hoisting is not what you want. Plus, using let and const appropriately can increase the readability of your code by implying which variables are meant to be changed and which are not.

Hope this helps.

Good Luck,