Introduction

In this blog article, we shall see various language features, introduced in ES2015(ES6) JavaScript version.

A list of a summary of the language features can be found in this previous ES6 and modern JavaScript .

Let’s look at let and const keywords.

1. let, const keywords

In ES6, the var keyword has been deprecated in favor of let and const keywords in variable definition, declaration and initialization.

let is used to declare block-scoped variables.

var pov = 180 // don't use this
let pointOfView = 180 // reassignable, do this
pointOfView = 360 // change

const behaves similarly to let except that once variables are declared and initialized, they may never be reassigned once declared and initialized.

// declare constants using const
const THREAD_COUNT = 18 // must be declared and initialized in one line
const MAX_THREAD_COUNT //  Uncaught SyntaxError: Missing initializer in const declaration 
// somewhere later: 
MAX_THREAD_COUNT = 18 

For object literals, changing values stored in object properties work but reassigning the declared object throws an error.

const hero = {
  name: 'Naruto',
  age: 15,
  jutsu: 'shadow clone justsu',
  residence: 'Hidded Leaf Village'
}

hero.name = 'Sasuke' alters the value stored in object property name of the hero object. However, reassigning the object like:

// reassigning the variable
// Uncaught TypeError: Assignment to constant variable.
hero = {
  name: 'Sasuke',
  age: 15,
  jutsu: 'Fireball Jutsu',
  residence: 'Hidden Leaf jutsu'
}

Summary

ES6 introduces let and const keywords in place of var keyword in declaration and initialization of constants and variables.

Use let to declare a variable that will change/be reassigned later and const for constants that are unlikely to change as the program executes.

Read more about 👉 Arrow functions