Let vs Var vs Const in Javascript

Let vs Var vs Const in Javascript

Image for post

I learned JavaScript well after the introduction of ES6 and thus have mostly used the ?let? and ?const? keywords in JavaScript for variable declaration by example, following the coders around me. I was told not to use ?var?, but wasn?t really told why. It?s a really common interview question though, so I?ve taken it upon myself to be the latest in a long line of people that write a technical blog on medium to explain something to themselves. Maybe you?ll get something out of it too!

Var declarations were the only type of variables before ES6, and Let and Const were introduced to fix some of its issues. The main differences with Var are its scope, its ability to be re-declared and updated, and the fact that it is hoisted. Now, as far as scope goes, var is globally scoped if it is declared outside of a function, functionally scoped if declared within one. For example:

Image for post

If pizza were declared outside of the function, we would have seen ?delicious? and all would be right with the world. So far, this doesn?t seem like a big deal. But when combined with the fact that var can be redeclared, it?s? easy to see where things can get messy. If we can redeclare a var that?s globally scoped at any time, one small mistake could ruin otherwise perfectly good code. This is a big reason why let and const are preferred. Another little unique wrinkle about var is the fact that it?s hoisted. I?m not going to go super deep into hoisting, but for our purposes, it?s a pretty simple concept. Take this for example:

Image for post

We get undefined instead of an error, because variables declared with var are ?hoisted? to the top of their execution context. This is not the case with let or const.

Let variables, unlike var, is block scoped, which means it scoped to a bunch of code surrounded by curly brackets. This can mean a function, or a loop or what have you. Another difference between let and var is that let can be updated, but not redeclared.

Image for post

This will not give us an error, but this will:

Image for post

This is the main difference between let and const. They?re both scoped the same, but const cannot be updated or redeclared whatsoever.

So just to recap, the main differences are: var declarations are globally or functionally scoped while let and const are block scoped. Var can be updated and redeclared, let can be updated but not redeclared, and const can do neither. Var is hoisted, while let and const are not.

That?s all folks! Thanks for reading.

13

No Responses

Write a response