Javascript: Let and Const over Var

In the olden times, the times before ES6 javascript only allowed us to declare variables using var like so

var x = 10

This makes sense var meaning variable is equal to 10. So why do we have to use let and const? Well the problem lies with how the variable is scoped. Variables declared with var can be reassigned and can be hoisted or declared before they actually occur from top to the bottom in your code.

Basically, you can never be too sure what the value of your variable is going to be if you are not extra careful what variables are being redeclared and which ones are not

Const

Variables declared with const are not able to be redeclared; their value is constant.

const a = apple

If you try to change the value of a to almond you will get an error. It’s been made apple and will now and forever be apple. However, there is one gotcha. Take for example the following array.

const dwight = [ 'beets', 'bears' ]

If I was to try to push 'battlestar galactica' into the array what do you think would happen?

dwight.push('battlestar galactic')console.log(dwightFears)

It logs [ ‘beets’, ‘bears’, ‘battlestar galactic’]! And what would happen if we try to remove the first element in the array ?

dwight.shift()console.log(dwight)

It logs [‘bears’, ‘battlestar galactic’]. But const isn’t supposed to allow variables to be changed so what’s going on here? Without going into the weeds, const assisgns a value in a specific place in memory. When we declare an array with const we are saying, keep this array in this place in memory. We can still manipulate the array, a primitive value like a string or number however cannot be manipulated.

Let

Using a variable with a let declaration is very similar to var except for two exceptions, you cannot use a variable before its declaration and you cannot redeclare a variable. This solves a lot of the unpredictability that var created.

Rule of thumb is use const as much as you can. You’ll be surprised at how often you can use it over let.

Happy Coding

Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store