Simple JavaScript: var, let and const

Simple JavaScript: var, let and const

 

In Modern JavaScript (ECMAScript)  var is being deprecated and replaced by let and const.  What follows is a simple explanation of the differences.

var and let are very similar. Think of let as an improvement of var.
In  the examples below I am using the name-value pair of myName (name) and ‘Windy’ (value).

var myName = ‘Windy’;
let myName = ‘Windy’;

var myName;
myName = ‘Windy’;

let myName;
myName = ‘Windy’;

var myName = ‘Windy’;
myName = ‘Williams’;

let myName = ‘Windy’;
myName = ‘Williams’;

All the above are valid, but the following example using let is not.

var myName = ‘Windy’;
var myName = ‘Williams’;  Permissible using var.

let myName = ‘Windy’;
let myName = ‘Williams’;   Not permissible with let.

In the example above var allows the reassigning of the name-value pair declaration of var  myName = 'Windy'; to var myName = 'Williams'; Thereby creating 2  variables with the same name but different values. This isn’t allowed in let; it will produce an error.

const is different.

const myName = ‘Windy’;  Value has to be assigned here as shown.

const myName;
myName = ‘Windy’;  Not, permissible using const the name-value pair has to be assigned.

Also, the name value pair can’t be reassigned, as in the example below, i.e the name-value pair has to remain constant.
const myName = ‘Windy’;
myName = ‘Williams’;  This isn’t permissible.

Featured Photo by Greg Rakozy on Unsplash

Journal →