Declaring variables is one of the first things we learn to do as programmers. For a long time, this was done in JavaScript with a singular keyword var
. With the release of ES6 we were given two more options for variable declaration: let
and const
. I started learning JavaScript after the introduction of these new keywords. When the topic of variable declaration came up in learning material, most resources mention var
in that you will need to recognize it when working with older code. They give a brief overview that explains that let
and const
solve some of the issues with using var
, tell you to prefer using them over var
, and then move on to coding.
For most learning material this is pretty much enough to get you up to speed and working on projects, but I think having the knowledge of why these different keywords exist is important. Many JavaScript interviews include questions about the keywords, and I have personally been caught off guard having to explain what would happen to variables declared with different keywords. More importantly, when working on a code base, its important to know what is going to happen to your variables.
Scope
An important concept to understand when talking about variable declaration is scope. Every variable that you declare in your code will have a scope. In fact, its one of the major differences between the use of different keywords to declare a variable. Let's take some time to understand what that means.
Per the MDN web docs, scope is defined as such:
The current context of execution. The context in which values and expressions are "visible" or can be referenced. If a variable or other expression is not "in the current scope," then it is unavailable for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.
Essentially what this means is that a variable's scope is where in your code it is available for use. They have a hierarchy which is why you can access global variables in an inside function, but not the other way around. So if variable scope is a major difference between declarations, what does that mean? Let's take a look.
var
in Scope
var
declarations can get scoped either globally or functionally/locally. Variables defined outside of a function will be available anywhere in your program, while those defined inside of functions will be available only in that function.
Another property of var
is that variables declared with it can be re-declared and updated. Take a look at the code below.
// this code
var name = "AJ";
var name = "Susan";
// is the same as
var name = "AJ";
name = "Susan";
As you see above, re-declaring a variable with var
is essentially the same as updating the value. This works great when you're working in the same scope, but we run into problems if we accidentally try and declare a variable with a name that has already been used elsewhere. Take a look at another example:
var message = "Hello!"
var count = 5;
if (count > 0) {
var message = "Hola"
}
console.log(message) // "Hola"
Inside our if
block, we create a message variable if our count
is greater than zero. Wait a minute though, it looks like we didn't realize that message
was already used somewhere else and we accidentally updated the value of a variable we might need for something else.
Let's see what happens when we use let
or const
instead.
Breaking down let
and const
In contrast to var
, both let
and const
are block scoped. Any code bound by curly braces is a block. This means when we declare a variable with let
or const
it's scope is whatever pair of curly braces it was declared in. Also, variables declared with let
can only be updated, not redefined like with var
. const
variables cannot be changed at all after their initial declaration. (There is a small exception here with objects)
So let's take a look at that code again using let
:
let message = "Hello!"
let count = 5;
if (count > 0) {
let message = "Hola"
}
console.log(message) // "Hello"
Since our if
statement is it's own block, we are able to declare a new variable that is scoped to the if
statement and it does not interfere with the variable we declared outside of it. With let
we don't have to worry about re-declaring existing variables. In fact even if we accidentally did this in the same scope, we would get an error saying that our variable has already been declared.
A Bit About Hoisting
The last thing I want to mention in terms of comparing var
, let
, and const
is hoisting. If you're not familiar, hoisting is the process in which JavaScript gathers the declarations in your code and brings them to the top of their respective scopes before executing any code. Did you notice I said scope? Since variables are hoisted to the top of their scope, variables declared with var
, let
, and const
are hoisted differently.
Variables declared with var
are hoisted to the top of their scope, and given an initial value of undefined
. This means that if you try and use the variable before it is defined in your code, you will be using a variable with a value of undefined
.
Unlike var
, JavaScript does not initialize a value for variables declared with let
. When a let
variable is hoisted, it is only declared, and so if you were to try and use it before it is initialized, you would get a Reference error
.
const
variables are almost identical to ones declared with let
with the minor difference that they cannot be re-declared or updated at all. There is one exception when dealing with objects where you are able to modify object properties, but you cannot update a const
object directly using the assignment operator. Since they cannot be changed, const
variables must be initialized when they are declared.
That's It!##
And that's all there is, now you have a deeper understanding of the major differences of variable keywords. I hope this was helpful for you!
If you liked this post, feel free to follow me elsewhere on Twitter, Github, or LinkedIn. Happy Coding!
Top comments (2)
Delicious post! Beside C and C++ are my core languages. I am enjoying Javascript-ing recently. Thanks for the tips.
Thanks for your detailed information about var, let, const