The Difference Between var, let, and const

I usually use var to declare a variable. Today, while reviewing some code samples, I came across let and const. I realized that I wasn’t sure what the difference was between them. So, I searched it up on YouTube and I found a Dabble Labs tutorial video. Here’s what I learned:

Var

Var was the only way to define a variable before the 2015 update. It’s the most common keyword to declare a variable in JavaScript.
Let’s talk about variable hoisting. Variable hoisting is when you call a variable before you define it. For example:

caller = "Aariv";
console.log(caller);
var caller = "Rohan";
console.log(caller);

If you were to run this code, here would be the output:

undefined
Rohan

For variable hoisting, using var will simply give you undefined.
Now let’s look at scope. Scope is when you define a variable inside a function and call it outside of the function. For example:

var randFunc = function() {
var points = 27;
}
console.log(points);

If you tried this code, it would give you this:

undefined

Same with scope. If you misuse scope, it will just give you undefined.

Let

Let was added in the 2015 update, along with const. Let is very similar to var, yet there are a few differences. If we ran some code:

caller = "Aariv";
console.log(caller);

The output would be a HUGE error, 10-15 lines of code. It’s not hard to miss. Same with scope. Personally, I prefer using let instead of var because it’s easier to find mistakes in your code. I might accidently miss undefined, but I’m not going to miss a huge error like that.

Const

Const is unlike let and var. Yes, they are all keywords that declare a variable, but const has an entirely different purpose. A variable defined with const can never be changed. If you run the following code, it may or may not throw an error, depending on the situation.

const playerOneScore = 0;
const playerTwoScore = 0;

if (playerTwoGoals > playerTwoScore) {
    playerTwoScore = playerTwoGoals;
}

if (playerOneGoals > playerOneScore) {
    playerOneScore = playerOneGoals;
}

If either player scores, the game will throw an error. The score cannot be changed because it is defined using const.

I hope you understand the different ways to declare a variable, as I now do. The next time you try programming, check your code to see if you are using the best way to declare a variable. If not, you will most likely get an error once you run it. Thanks to Dabble Labs for a great video. If you would like to see it yourself, I have included the video in this post.

Leave a Reply

Your email address will not be published. Required fields are marked *