avatarDr. Derek Austin 🥳

Summary

This context explains the differences between let, var, and const in JavaScript and their respective scopes.

Abstract

The context discusses the three ways to create variables in JavaScript: let, var, and const. It explains that let is block-scoped, var is function-scoped, and const is block-scoped but immutable. The context provides examples of each type of variable and explains concepts such as hoisting and closures. It also mentions the consequences of forgetting to use a keyword when declaring a variable. The context concludes with a summary of the differences between let, var, and const and provides additional resources for further reading.

Bullet points

  • There are three ways to create variables in JavaScript: let, var, and const.
  • let is block-scoped, meaning it occurs within a code block.
  • var is function-scoped, meaning it occurs within a function.
  • const is block-scoped like let but immutable, meaning its value cannot be changed.
  • The concept of hoisting refers to the fact that all var and function declarations are pulled to the top of the code when it is run.
  • A closure is a function that has access to variables in its parent scope, even after the parent function has finished executing.
  • If a variable is declared without a keyword, JavaScript tries to help by making a global var.
  • It is generally best practice to use let or const instead of var in JavaScript.
  • Additional resources are provided for further reading on the topic.

How to use let, var, and const in JavaScript

There are 3 ways to create variables in JavaScript: let is block scope, var is function scope, and const is block scope but immutable (i.e. a constant).

Photo by François Kaiser on Unsplash

The difference between let, var, and const is a common interview question, a frequent source of confusion, and hard to explain.

Recently I attended a 15 minute lightning talk just on this topic, with many great details on JavaScript parsing, execution context, and hoisting.

But, I found that I was still having trouble explaining the concept myself until I wrote it down this way:

  • let == block scope
  • var == function scope
  • const == block scope like let but immutable

Here is a simple example:

Let us examine what let, var, and const actually mean in JavaScript.

Photo by Bryan Minear on Unsplash

let == block scope

Block scope means it occurs within a code block.

This is how many programmers expect variables to work, because most programming languages only have block scope.

Initializing variables with the let keyword is really useful for when we want to limit access to a variable or only need a variable temporarily.

A great example is when writing a for loop:

Photo by Ankush Minda on Unsplash

var == function scope

Function scope means it occurs within a function.

In JavaScript, because of the concepts of execution context and hoisting, function scope is different from block scope.

Compare this to if the var keyword is not included in the function:

Photo by Toa Heftiba on Unsplash

const == block scope like let but immutable

Like let, const also uses block scope. But const creates a constant, an immutable variable whose value cannot be changed.

Here, immutable means the reference cannot be changed, since primitive values like numbers and strings are also immutable in JavaScript.

Note that objects are an exception, because their properties can still be changed. Depending on personal preference, some programmers treat const objects as actually immutable and try not to change their data at all.

Here is an example of using the const keyword to initialize a variable:

Photo by Drew Dau on Unsplash

A vocabulary lesson: hoisting and closures

No article on JavaScript lexical scope would be complete without a brief mention of the concepts of hoisting and closures.

What is hoisting?

The term “hoisting” refers to the fact that all var and function declarations are all pulled to the top of the code (or hoisted) when the code is run.

[W]hen Javascript compiles all of your code, all variable declarations using var are hoisted/lifted to the top of their functional/local scope (if declared inside a function) or to the top of their global scope (if declared outside of a function) regardless of where the actual declaration has been made. — Sunil Sandhu in JavaScript in Plain English

Note that the variable declaration is hoisted, but the value assignation is not. That means hoisting can produce results that you might not expect:

But removing a var keyword changes the behavior due to hoisting:

This does not happen when using let or const. Here is an example:

Photo by Hannah Busing on Unsplash

What are closures?

A “closure” contains all the variables that are in scope at the time that the function definition is created. It maintains that same lexical scope.

When a function returns a function, that is when the concept of closures becomes more relevant. The returned function has access to variables that are not in the global scope, but they solely exist in its closure. — Olivier De Meulder in Daily JS

Closures are like a backpack. Functions come with little backpacks containing all the variables in scope when the function was created.

Here is a quick example of closures in action:

When the variable multiplyByFive gets declared in the local context, it is assigned a function definition and a closure.

In this example, the variable number is part of the closure.

So now when multiplyByFive is called and executed, it has access to the variable number from its closure as well as the variable innerNumber that was passed as an argument and thus is able to return the product.

Photo by Artur Aldyrkhanov on Unsplash

What if I forget to use a keyword?

In that case, JavaScript tries to help you out by making a global var.

Usually this is considered a bad thing, because now that variable could be accessed (and changed!) absolutely anywhere else in the code.

In this case, hoisting works a little differently in that there is no variable declaration to hoist to the top of the code. Thus, until the function is executed the variable declaration is not defined.

Compare with explicitly declaring the variable, even at the end of the code:

Note that “use strict” and ESLint both catch this error, but it is generally best practice to use let or const instead of var in the first place.

Photo by Sébastien Bourguet on Unsplash

To recap:

var is function scope. let and const are block scope.

Function scope is within the function. Block scope is within curly brackets.

— Joe Cardillo on his Medium blog

Additional resources:

Dr. Derek Austin is the author of Career Programming: How You Can Become a Successful 6-Figure Programmer in 6 Months, now available on Amazon.

JavaScript
Programming
Technology
Software Engineering
Data Science
Recommended from ReadMedium