Tuesday, November 6, 2018

TypeScript - ES6 - let and const

The following syntax change has been introduced by  ES6 which has been included in TypeScript:

  • let 
  • const

These are new ways to create variables and constants. Till now, in JavaScript ES5 we have been creating variables using the var keyword.

var myCity = "Hyderabad";

In ES6, we use the let keyword:

let myCity = "Hyderabad";

The difference between let and var is in the scope of the variable.
let
block scope variable
var
global scope variable


A variable declared with const keyword cannot be modified after initializing it. Hence, it is called a constant. Consider the example:

const cityArea = 12;
console.log("cityArea = "+cityArea);

cityArea = 24;


This will emit the following error on compilation:

$ tsc
city-App.ts:7:1 - error TS2540: Cannot assign to 'cityArea' because it is a constant or a read-only property.

7 cityArea = 24;
  ~~~~~~~~

$

now, if we remove the re-initialized portion of the code. The compilation will occur.

const cityArea = 12;
console.log("cityArea = "+cityArea);

$ tsc
$

const keyword helps us to create a immutable data structure.


No comments:

Post a Comment