JavaScript: Var, Const, and Let.
Why do we need all 3?
As new developers, we learn that “JavaScript lets you do just about anything you want” with your code. That’s great! However, having such a broad scope of capabilities leaves the door wide open for confusion as you get deeper and deeper into an app.
The var, const, and let statements are prime offenders when it comes to creating confusion. To new developers, the statements often seem interchangeable! Once you understand them though, the distinction can really make a difference in your code.
Var
Var statements can mean whatever you need them to. Once you declare them and define them, they hold that value until you need them to change. They can also be both globally and locally declared! This means that they can appear both outside and within a function. Let’s look at the following examples to understand what I mean by this:
Whether the statement is made alone or within a function, both are valid. Additionally, var statements can be changed at a different point in the document! It is important to note, however, that a var statement can only be changed within the same scope (position in the document) that it was made in the first place. For example:
Const
Const statements don’t like change. Once they have an identity, they will stick with it until the end (and they will cause errors if you try to change them). A const statement is meant to be a constant reference in your document.
So if we have a const like this first one, the second statement is invalid even though it is at the same scope.
A const may be updated, however. So a const that is an object may have attributes modified as long as the object remains the same; a const that is an array may have attributes added to it, etc. Here are a couple examples of this in action:
Let
Let likes to go with the flow, much like var. The big difference is that let plays much better with const than var does. So if a variable needs to changed based on certain parameters in order to define a const, let is your best bet. Let’s see what that looks like:
In this example, the variable “greeting” needs to change based on certain parameters. If this is someone that we don’t know well, we’ll “let” our message be “How are you?” If this is someone that we know, we add some personalization and we “let” our message be “Hi (name), how are you?”
As I said, this works much like var. Just try to stick to let if you are also using const.
Conclusion
I hope that this has helped clarify the difference between var, const, and let in JavaScript. For additional information, please refer to their Mozilla documentation here: