Let and Const

What is Const and Let?

We've historically defined variables using var

var name = "Bob Evans";

In ES6, we never need to use var again. It is going to be best practice to only use let and const.

const is used to declare variables that will never be re-assigned.

let is used to declare variables where the value could change at some point.

const name = "Bob Evans";
let address = "123 Fake Street";

Why use const and let?

In complex JavaScript programs, we will be using many variables. Because of these new variable declarations key words, let and const, we have more control over those variables.

Const and let also makes our code more readable. We can explicitly show what variables we expect to be altered, and which variables should stay the same.

For example, imagine we are writing a program to identify vowels. We would use const to declare the array of vowels because vowels will never change. They will always be: a, e, i, o and u.

const vowels = ["a", "e", "i", "o", "u"];
Scoping of Const and Let vs. Var

Another important thing to understand about const and let is that they are locally scoped whereas var is globally scoped.

For example:

function localScope(){
  if(2 === 2){
    let local = 'dog'
  }
  return local;
}
localScope()

//returns 'local' is undefined

but if it were the same function using var:

function localScope(){
  if(2 === 2){
    var local = 'dog'
  }
  return local;
}
localScope()

//returns 'dog'

Practice

change all the following vars to either const or let

var name = "Ben";
var age = 24;
var dateOfBirth = "feb";

var statuses = [ 
  { code: 'OK', response: 'Request successful' },
  { code: 'FAILED', response: 'There was an error with your request' },
  { code: 'PENDING', response: 'Your reqeust is still pending' }
];
var message = '';
var currentCode = 'OK';

for (var i = 0; i < statuses.length; i++) {
  if (statuses[i].code === currentCode) {
    message = statuses[i].response;
  }
}