Javascript's const keyword

in #programming7 years ago (edited)

Javascript provides you with a keyword called const that will allow you to declare constants that may not be changed after their initial assignment.

Here are a couple of examples:

const x = 10;
console.log(x);
//You will get the value 10 printed on the console

x = 11;
console.log(x);
//You will get an error message on the console
//SyntaxError: Assignment to constant variable: x at 30:0

Declaring objects with the const keyword will also have a similar effect except for the fact the you will still be able to modify the objects properties or add properties to it

const obj2 = { a: 1, b:4, c: 10 };

obj2.c = 100;
obj2.d = 400;

console.log(obj2);

//Here you will get the object{ a: 1, b: 4, c: 100, d: 400 }printed on your console.

However, trying to assign (remember the word is assign here) to the variable will throw an error:

obj2 = { e: 4 };

console.log(obj2);

//'SyntaxError: Assignment to constant variable: obj2' printed on your console

I hope this helps!

Sort:  

Also worth noting, const declarations are block scoped (not function scoped like var), and cannot be accessed before declaration due to temporal dead zone (unlike var). This is a nice post describing the behaviour of var vs let vs const - https://dmitripavlutin.com/javascript-hoisting-in-details/

Thanks Petar.