DEV Community

Joe Steinbring
Joe Steinbring

Posted on • Originally published at blog.jws.app on

Var vs let vs const in JavaScript

The next post in our X vs Y vs Z series is var vs let vs const. I’ve wanted to cover this for a little while. Let and const were added to JavaScript with ECMAScript 6. Var has been around a bit longer.

Var is used to declare a function-scoped or globally-scoped variable. Var declarations are processed before any code is executed. Let’s take a look at a quick example.

In the above example, there is a lot going on.

If you click button #1, it shows you the value of pi. When you click on button #2, it shows you my name. When you click on button #3, it shows you a sentence based upon the two prior values. Using button #4 and button #5, you can change the value of pi and my name. When you click on button #3 again, your changes are reflected in the sentence. The values in this first example are using var to define them.

Next, let’s look at the same thing but let’s use let instead of var.

This example works exactly the same as the first one. You can load the values and change them. Now, let’s see how const works in the same scenario.

Now, defining everything using const makes all of the values immutable. You can define their initial value but you can’t change their value. That means that buttons #1, #2, and #3 work fine but #4 and #5 result in errors.

The benefit of using let and const over just var is that you can signal your intentions for the values. If you have something that shouldn’t change it’s value, use const and you won’t be able to change it’s value.

Now, there is an exception to keep in mind with const and objects.

In the above example, we are defining me using const but we are later changing it. You can add properties to a constant object and you can even change the value of what you added. It’s something to keep in mind.

The post Var vs let vs const in JavaScript first appeared on Blog.jws.

Top comments (1)

Collapse
 
arvindpdmn profile image
Arvind Padmanabhan

Another useful thing to know is hoisting: devopedia.org/hoisting
Quote: (in the context of hoisting) Unlike the var keyword, let and const keywords don't initialize variables with undefined.