If you've spent any time learning Javascript you've probably seen three ways to declare a variable. This guide will show you an in depth look at the behaviors of 'var', 'let' and 'const'. Afterwards, you'll be setting variables appropriately and confidently.
For starters...
'Let' and 'const' are apart of ES6 (ECMA script 6). This is the latest approved standardization for Javascript that was released in 2015. ES5 was released in 2011. Modern Javascript frameworks like React and Vue utilize ES6. So it's a great time to jump on board the ES6 bus.
Using 'var', 'let' and 'const' is as easy as this:
var pie = 'apple'
let pie = 'apple'
const pie = 'apple'
Var-y funny
Let's take a look and see how a 'var' behaves. Var is scoped to the entire function it's in.
function count() {
for (var i = 0; i < 3; i++) {
if (true) {
console.log(i);
}
}
console.log(i);
}
count();
Can you see what's wrong in our console?
On line 7, the 2nd console.log(i) is saying i is equal to 3. This is a problem since our for loop should stop when it hit the 3rd loop. Instead of doing that, our 'var' is scoped to the entire count function.
Watch happens when we change our 'var' in our for loop to let:
function count() {
for (let i = 0; i < 3; i++) {
if (true) {
console.log(i);
}
}
console.log(i);
}
count();
We now get a ReferenceError on the 2nd console.log(i). This is actually what we want. Outside of the for loop, the parent function shouldn't care that we declared a function named i. That's because 'let' is scoped to the code block it lives in. 'Const' is the same way. 'Var' can get tricky since it's scoped to it's function AND it can also collide with variables set in the window. In other words, two variables named the same thing will cause errors in your program.
If you don't know, there is a window object that hosts a ton of behind the scenes stuff. Open up your console on your web browser and type in window to see it all.
You can imagine we'd get some errors working with larger applications that utilize window if we're using vars everywhere.
So hopefully you can begin to see why it's best practice to stick to setting variables with 'let' and 'const'.
Let's dig in
As you may have guessed 'let' allows the program to update it's value.
let pie = 'apple'
//...
pie = 'pecan'
console.log(pie)
Here we declared a variable called pie and set it's value to the string apple. Later on in our app, we updated the pie variable to pecan with no issue. Console logging pie shows us we're set to have pecan pie. Yum!
I const stop eating...
Let's try the same thing in console with 'const', instead of let.
const pie = "apple";
pie = "pecan";
console.log(pie);
Well no pie for us. That's because we said pie should never update it's value of 'apple' by declaring it with 'const'. And this is a good thing! Our variable is protecting itself against future modification. We all know apple pie is the best pie and should never be replaced. :D
'Const' safe guards your variables by throwing an Uncaught TypeError.
Can we scrape 'var' in the trash can?
Why doesn't Javascript just take 'var' out and replace it with 'let'? That's a good question, but the answer is that it would be absolute chaos. Imagine all the websites and apps utilizing 'var' in legacy code. Removing 'var' support would just be such a nightmare for everyone. So, just like mom's giant papier-mâché turkey centerpiece, it stays for the full course meal.
TL;DR (doggie bag version)
Let is great to use when you say it's OK for the variable to be updated.
'Const' is great to use when the variable should never update.
'Let' and 'const' are scoped to the code block that they live in.
Using 'var' is like taking a bite out of pie that's been left out for a week. It is scoped to the entire function, regardless of whatever code blocks are in it. So you're probably going to have issues using it and eating old pie.
Get in the habit of using 'let' and 'const'. It will save you some headache in your career as a Javascript developer.
More dessert please...
What if you wanted to update a variable in a loop (or a code block further into the function)? Piece of cake, just declare the variable at the beginning of the function:
function chowDown() {
let capacity = "empty";
let inches = 42;
for (let i = 0; i <= inches; i++) {
if (i == inches) {
capacity = "full";
}
}
console.log("my belly is now " + capacity);
}
chowDown();
Photo by Priscilla Du Preez on Unsplash
Top comments (7)
One other small but important thing is that const only means immutable, never can be changed, for primitive values.
This is not the case for objects and arrays! The properties can change. It refers to reference in memory. I'm not sure if there's any reason not to favor let for objects and arrays for this reason. Save const for primitives. It's a clearer signal to other devs of what is truly constant.
You are absolutely correct Dan! I call it the sneaky const array, 😂. I forgot to mention that in this article, but I'll update it soon. Kudos!
Great article! I think this was a sticking point for me when first learning JS.. I'm also glad to see you mention var, people just starting out with ES6 should still learn it so they can still know how to work on legacy code if need be (just like you said). Awesome work!
Thank you for the kind words! It's a privilege to have anyone read what I've learned along the way. :D
This is really helpful-- I've been using let and const from the beginning so remembering the differences in functionality between them and var can be confusing.
Thanks! Yeah, I felt it's helpful to reintroduce these concepts, to even those comfortable using them. I know it helped me. :D Thanks for reading and the kind words!
Hello Brett, I am delighted with your articles in Dev.to, I would like to talk about programming, are you willing?