Const in angular 4

Const in angular 4

const is a new keyword which declare a variable as constant over time.

Declaring a const variable

we can declare variable as constant but unlike let and var it must be immediately initialized. we can't change afterwards.

if you try to declare without initialise throw the SyntaxError


 const myvar; // SyntaxError : missing initializer in const declaration

if you try to change after declare and initialised, we get TypeError


const myvar = 1;

myvar =2; // TypeError : Assignment to constant variable

const is immutable variable. we can't change over time. 

if variable myvar point to an object, we cna't make myvar point to another object.


const myvar = {};

myvar = {};// TypeError: Assignment to constant variable

But we can however mutate make changes mycar point like


cosnt myvar = {};

myvar['prop'] = 'Moo'; // this is work

if you want to myvar immutable we have to freeze it using object.freeze();

cosnt myvar = object.freeze({});

myva.prop = 123;

console.log(myvar.prop);

if you freeze an object we can't change it.

0 Comments

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed

>