Simplified JavaScript: How do I use var, let, and const?

Written by MCapoz | Published 2017/10/25
Tech Story Tags: javascript | simplified-javascript | var | let | const

TLDRvia the TL;DR App

Before reading this post, consider reading my earlier posts on hoisting and closures. They might give you some background information you’ll need to understand this post.

I first stumbled across ES6 a few months after I had begun to learn JavaScript. When I realized the syntax had changed, I felt frustrated. (This was before I had dipped my toe into the JavaScript framework ecosystem). I didn’t understand why JavaScript’s syntax needed to be updated. I hardly grasped using var, and I suddenly had to learn let and const?

I was missing the point. let and const behave differently than var. Their addition to JavaScript allows us to write more expressive, elegant, and cleaner code.

I wish someone had handed me a simple explanation of the difference between these three ways of declaring local variables. So I wrote one for you!

var

In ES5, developers declared local variables using var. var is scoped to the nearest function block. That means that the code below will not error out. Instead, it will return 5.

const arr = [1, 2, 3, 4, 5];

for (var i = 0; i < arr.length; i++) {

};

console.log(i) // 5

This happens because i is scoped to the nearest function block, not the nearest enclosing block, so console.log(i) has access to it.

More importantly, var can be reassigned after it’s initial definition. That means I can assign a variable like var language = "JavaScript" and then later on in my program, I can change var language to var language = "Ruby".

let

let was introduced in ES6. It’s similar to var, since it can be reassigned, but it’s scoped to the nearest enclosing block, not the nearest function block.

That’s different from var. If we use the same example from above, but replace var with let, we’ll see an error.

const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {};

console.log(arr[i]); // ReferenceError: i is not defined

This happens because i is scoped to the for loop, not the function block.

Let is great to use it whenever I’m defining a variable that I know I’m going to reassign.

const

I use const when I’m not going to reassign a variable. Let’s look at our example once more:

const arr = [1, 2, 3, 4, 5];

for (let i = 0; i < arr.length; i++) {console.log(i)};

// 1 2 3 4 5

In the example above, i is reassigned every time it loops through the for loop. arr, on the other hand, is never reassigned, so I used const.

Rule of Thumb

Now that let and const are here to stay, I’d avoid using var at all. Using let and const allow you to clearly express your intention. Expressiveness will lead to cleaner, more elegant code.

More Reading


Published by HackerNoon on 2017/10/25