The Difference between Let and Const in JavaScript

If you have recently started to learn Web Development, or in particular JavaScript, you might come across two different types of variables: Let and Const. Let and Const was introduced quite recently to replace the old Var variable assignment. If you are like me and you have started with a Web Development Course that is a bit dated and still uses Var for variable assignment, you will be baffled once you come across something that uses Let and Const. Gladly, it’s easy to explain the Difference between Let and Const in Javascript.

 

The Difference between Let and Const in JavaScript

Let’s first talk about what Let and Const actually mean. Let stands for “letting” and Const stands for “Constant“. That alone should already give you a hint if it doesn’t let me break it down for you with an example.

// Dear computer, can you please
let
// this
day = "Wonderful"

Which obviously translates to:

let night = "Wonderful"

Pretty logical, or isn’t it?

Const, on the other hand, explains itself pretty well. You use Const, or Constant for that matter, for variables that do not change. Let me give you another example.

let isSnowing = true

isSnowing = false

console.log(isSnowing)

Can you guess what the output of this is? If you guessed false, you are right.

Difference Between Let and Const

We first assign isSnowing the boolean value of true, and then re-assign it the value false a line below. The ultimate result is false.

Now, what happens if we refactor this code to use Const instead of Let?

const isSnowing = true

isSnowing = false

console.log(isSnowing)

We receive an error message:

 

That means JavaScript knows that we are trying to modify a Constant variable so it won’t run the code and throws an error at us. By now you probably can see some scenarios where this might be useful?

If we go ahead and comment out isSnowing = false, our code will run:

const isSnowing = true 
// isSnowing = false 
console.log(isSnowing)

Why Const and Let were implemented?

If you have asked yourself this question by now, I got the answer to you: Readability.

To understand the difference between let and const, you have to simply think about the readability of code. If somebody else has to work on your code and sees a Const variable, he immediately knows that this is a fixed value and it is not going to change later on in the code, making it much easier for him or her to understand your code, whereas the opposite is true for Let.

Once I dug a little deeper it made perfect sense to me as well.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: