Javascript: let, var and const. Part 1

To start off this discussion of what let, var, and const do in Javascript and why theres even more than one way to declare variables, I’ll repeat what my software engineering teacher said to me: “Always start with const and move to let if you get an error.” This has stuck with me since and I use it in practice every day, but it got me thinking. Why is this so, and how can I better understand the intricacies of these very important keywords?

Let’s back it up a bit shall we? When Javascript received its last major revision with its release of ES6 in 2015, let and const were newly introduced to the Javascript community for use. Prior to this, the only way to define a variable was with the use of var. Let’s discuss the fine print:

Var — “the o.g.”

Var can be both locally and globally scoped but it cannot be block scoped, which means you could not have block scoping prior to 2015. In addition to not being block scoped (which we’ll discuss in a minute), var can be re-defined and told to equal something totally different than what it was just a few moments ago. This can jumble things up a bit:

var greeting = "Good afternoon, world!"
var timeOfDay = "10"
if(timeOfDay === 10) {
var greeting = "Goodnight, world!"
}
console.log(greeting) // "Goodnight, world!"

As we can see, greeting completely changed its value, regardless of the fact that we already declared it on line 1 as a global variable. This is allowed to happen because var can be re-defined and it is not block scoped, meaning — “variables declared inside a block, “{}” can be accessed from outside the block.” Well what the heck? Can we solve this problem with the use of const and let? Sure can!

Let

A key difference that we can distinguish right away from var, is that let is block scoped and it cannot be re-defined. If we use the same example above but swap some variables out with let, this is what would happen instead:

let greeting = "Good afternoon, world!"
let timeOfDay = "10"
if(timeOfDay === 10) {
let greeting = "Goodnight, world!"
console.log(greeting) // "Goodnight, world"
}
console.log(greeting) // "Good afternoon, world!"

In this example, greeting changed inside of the block of code within our if statement, but kept its initial value that was defined on line 1 outside of that block, because let is block scoped.

Const

Like let declarations, const declarations can only be accessed within the block they were declared. Along with this, const can never be re-defined, which can save confusion in the future by not allowing the initial value to be changed by mistake. This makes const and let clear choices in variable declaration if you know you’ll never need to re-define it, while also serving as a signal to other developers who may be looking at your code. So to echo the words of my instructor once again: “Always start with const and move to let if you get an error.”