DEV Community

Tori Crawford
Tori Crawford

Posted on • Updated on

Breaking Down ES6: let and const

Four years ago today, ECMA International released the 6th major version of ECMAScript. This version was officially named ECMAScript 2015, but is commonly referred to as ES6. Ding. Ding. Ding. I hope that rang a bell for you and turned on that light of curiosity.

While looking for a job, I have noticed that most of the time, when a company lists JavaScript as a job requirement, they write it as “JavaScript (ES6)”. From my experience, I have learned that the knowledge of ES6 principles/standards are widely sought after as a job requirement by many companies. Due to this, I am writing this blog series about ES6 in order to

  1. Sharpen my own skills and knowledge of ES6 rules.
  2. Help teach and/or strengthen your skills on the topic.

Getting Started

This blog post will be the first in this series, so I thought I would start by breaking down ES6’s introduction of let and const. Before we dive deep into each of these keywords, I want to mention ES6’s introduction of block scope.

Block Scope

Before the introduction of ES6, we used var to declare all of our variables in JavaScript. Variables declared using var could fall under global scope or local scope.

Global Scope - A variable declared outside a function is considered to be a global variable having global scope, meaning that “all scripts and functions on a web page can access it.”

Local Scope - A variable declared within a function is considered to be a local variable having local scope, meaning that it “can only be accessed from within the function” it is declared in.

With those explanations out of the way, let’s discuss block scope. A variable declared using let and const are considered to be within block scope. This means that the variable can only be accessed within the block it had been declared. What is a block, you may ask? Well, a block is normally found when you see curly brackets {}. A block could be within conditional statements, for and while loops, etc.

To keep it simple, as an example, if a variable is declared using let or const within an if statement, the variable can only be accessed within that if statement's block scope.

Note: If you would like a more in-depth look at these three scopes, I have also written this article:

Now that we have block scope defined, let’s move on to our two keywords, let and const.

let

As I have already stated, let is considered to be a block scope variable. Similar to var, let allows the variable to be reassigned within its scope.

function testLet() {
  let cat = Mr. Whiskers; 
  console.log(cat) // “Mr. Whiskers”;

  cat = Tuna;
  console.log(cat) // “Tuna”;
}
Enter fullscreen mode Exit fullscreen mode

While the variables defined with let act similar to var with reassignment, it does not act similar to var when it comes to re-declaration. var variables can be re-declared within the same scope, while let variables do not allow this.

function testLet() {
  let cat = Mr. Whiskers; 
  console.log(cat) // “Mr. Whiskers”;

  let cat = Tuna; // SyntaxError: Identifier ‘cats’ has already been declared
}
Enter fullscreen mode Exit fullscreen mode

let variables can, however, be declared with the same name inside a child block element within the overall parent block scope. Why is this? Well technically, this would be considered another block scope and a variable that is declared within this scope cannot be accessed outside of it.

function testLet() {
  let cat = Mr. Whiskers;

  if (cat) {
    let cat = Tuna;
    console.log(cat) // “Tuna”
  }

  console.log(cat) // “Mr. Whiskers”
}
Enter fullscreen mode Exit fullscreen mode

Note: It is not common practice to use the same variable names for multiple variables within the same project.

With all of that being said, we can still re-assign variables new values within their children block elements. Why is this? This is because we are still technically within the variable’s block scope, and it can be accessed anywhere inside its scope.

function testLet() {
  let cat = Mr. Whiskers;

  if (cat) {
    cat = Tuna;
    console.log(cat) // “Tuna”
  }

  console.log(cat) // “Tuna”
}
Enter fullscreen mode Exit fullscreen mode

Variables declared using let can be declared without assignment, similar to that of var. This means that the variable has been declared but not yet defined, which will output a value of undefined.

function testLet() {
  let cat;
  console.log(cat) // undefined

  cat = Mr. Whiskers;
  console.log(cat) // “Mr. Whiskers”
}
Enter fullscreen mode Exit fullscreen mode

Last but not least, let’s talk about variable hoisting. When using var, variables are hoisted with their definitions, which means they float to the top of the scope and are available at any point in that scope. Variables declared with let are not hoisted in the same way. The declaration exists but the value/definition does not, so if you attempt to call the variable before it has been declared, you will receive a ReferenceError.

function testLet() {
  console.log(cat) // ReferenceError: cat is not defined
  let cat = Mr. Whiskers;
}
Enter fullscreen mode Exit fullscreen mode

const

Again, variables declared using const are considered to be a block scope variable. Unlike let and var, const does not allow reassignment. Using const “is a signal that the identifier won’t be reassigned.”

function testConst() {
  const cat = Mr. Whiskers;
  console.log(cat) // “Mr. Whiskers”

  cat = Tuna; // TypeError: Assignment to constant variable 
}
Enter fullscreen mode Exit fullscreen mode

const also doesn’t allow you to declare a variable without initializing it, which differs from both, let and var.

function testConst() {
  const cat; // SyntaxError: Missing initializer in const declaration
}
Enter fullscreen mode Exit fullscreen mode

Similar to let, const cannot be re-declared within the same block scope.

function testConst() {
  const cat = Mr. Whiskers;

  const cat = Tuna; // SyntaxError: Identifier ‘cat’ has already been declared
}
Enter fullscreen mode Exit fullscreen mode

Also similar to let, const can also declare a new variable with the same name within a child block element, because the variables declared within that block scope are not available outside of it.

function testConst() {
  const cat = Mr. Whiskers;
  console.log(cat) // “Mr. Whiskers”

  if (cat) {
    const cat = Tuna;
    console.log(cat) // “Tuna”
  }

  console.log(cat) // “Mr. Whiskers”
}
Enter fullscreen mode Exit fullscreen mode

Now, although a variable declared using const cannot be reassigned a value, if the value of the variable is set to an object or an array, the values within the object or array can be updated. In simple terms, as an example, the value of a key within an object can be changed or an array can be added to.

function testConst() {
  const cats = [Snowball];
  console.log(cats) // [“Snowball”]

  cats.push(Mr. Whiskers, Tuna)
  console.log(cats) // [“Snowball”, “Mr. Whiskers”, “Tuna”]
}
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

When it comes to declaring variables, I have taken the stance that I will no longer be using var, as it can become kind of messy due to the fact that you can declare the same variable 1000x within the same scope. This can cause issues and easily break code. It can also look very messy to another dev who wants to contribute to your code.

If you have no desire to ever change the value of a variable, use const. For counters or in for loops, let would be perfect to use. In the end, this is all based on personal preference. Just keep in mind that if your code is public, make it clean and easy to follow for everyone, not just you.

I hope this has been helpful, I know it has been for me thus far. If there is anything that you see that needs rewording or added in, please feel free to let me know, as I am still learning!!!

Sources

var vs let vs const in JavaScript
JavaScript ES6+: var, let, or const?
ES6: Let and Const
let
const
ES6 - Variables
JavaScript

Top comments (2)

Collapse
 
amarok24 profile image
Jan Prazak

Hi, nice article!
I just wanted to point out that

  let cat = Mr. Whiskers;

leads to illegal character error, because of using another double quotation marks.

Collapse
 
alexpaper profile image
alexpaper

Very usefull and readable explanation, I also found this video thanks
youtu.be/oqjDF0As0Ec