Javascript Upgrade: let/const


This is part of my series about upgrading my Javascript skills.

  1. Previous:
  2. Javascript, I hardly knew ya
  3. Javascript upgrade Day 1

First up I will be learning about let and const but to be honest I’m already pretty comfortable with both.  I’ve been aware of both for some time and earlier in the week I learned about let/const in detail on along with information about variable hoisting.  Beyond that it fits in pretty well with my experiences with other languages I’ve used.

Just quickly so I lock it in.  Hoisting is where Javascript moves all var whatever lines to the top of the current scope so top of a function if you’re in one or top of the current script if you’re in the global scope.  I don’t plan to use var anymore going forward so this will possibly explain some weirdness I see in other code but I don’t plan for it to be relevant to my own code going forward.

let/const allow you to define variables in Javascript that use block scoping.

function example(){
  var x = 1;
  if(x == 1) {
    var x = 2;
  console.log(i); //2


function example(){
  let x = 1;
  if(x == 1) {
    let x = 2;
  console.log(i); //1

As you can see in the second case the x inside the block has its own scope and doesn’t change the x outside the block.

const is for constants.  So if you need a “variable” but you aren’t going to change the value at all use a const.  An example might be the url of an API.  You want it to be in a variable so you only have to change it in one place but it’s never going to change during execution.  As someone that started out coding C I’m familiar with constants so this again was luckily easy for me to grasp.

I hope the rest of it fits as easily within my existing mental models but I know they won’t.  let/const were the low hanging fruit which is I guess why they came first.

About the author

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

By shawn

Other Things