Javascript - Block Scoping with let and const

Introduction

Block scoping means that a new scope is created between a pair of { }.

The variables declared using the keywords let and const only exist within the innermost block that surrounds them.

In the following example,

let nbr = 42; 
{ 
     let nbr = 1000; 
} 
console.log(nbr); 

The value 42 is printed to the console.

The second nbr variable is scoped to the block within which it is declared and does not affect the nbr variable outside of the block.

const

const creates immutable variables.

The values of the variables created using const need to be assigned during declaration and cannot be changed later in the program.

Consider the following example:

const value = 42; 
console.log(value);   // 42 
value = 1000;         // TypeError 

Trying to change the value of a const variable will throw a typeerror.

Changing an immutable binding in strict mode causes an exception SetMutableBinding().

Without initializing the const variable will throw an error. Consider the following example:

const item;  // SyntaxError: Missing initializer in const declaration 

If you need a constant with an undefined value, you'd still have to do something like this:

const value = undefined; 

Quiz