Const vs Let vs Var

 Const vs Let vs Var in Javascript. Which One Should You Use?




When we declare a new variable in JavaScript, we can either use constlet, or var. Each of these is used for something different and some might be needed in specific situations depending on what you’re working with. Today, we will take a look at the main differences between constlet, and var as well as when you should use which to avoid running into errors

Const

We’ll kick this off by starting with const which is probably the easiest of the three to understand as well as the one that I typically use the most. Const was first introduced into JavaScript when ES6 was released back in mid-2015 and has changed the ways that variables work ever since.

Basically, when you assign a value to a variable when using const, it means that you cannot give that variable another value later on. In other words, if you try to change a const variable, you will get an error thrown back at you. If you set a const statement inside of a block, however, it will only remain inside of that block.

Since const is block-scoped, this means that anything you try to do with a const variable can only be used within the block of code where you initially wrote it.

Let

Similar to constlet also works in terms of block scope. However, it is also similar to var in the fact that let does allow you to change its value later on in your code.


Var

Before the days of ES6, the way that we would declare a variable was with var. Var is no longer used as much as it used to be since the introduction of let and const, but it still hasn’t been removed from JavaScript and has some unique uses.

var and let are very similar in the fact that you can reassign a value later on. The main difference between the two though is that let deals with block scope whereas var deals with global scope or function scope depending on where it’s declared. As long as your variable isn’t declared within any function, var can be used again anywhere else in your code.

Also unlike letvar allows you to declare the variable as many times as you want and there will be no errors thrown at you. This means that the example above with let gave us an error whereas this example below will not.

Comments