ES-6 introduced the support for immutable variables or constant variables. Constant variables are not a new concept in programming and have been in existence in most of the programming languages of today.
If while programming you come across a scenario where you don’t want somebody to change value of a variable then it makes sense to declare the variable as constant. You must understand that you cannot reassign a constant variable to a new value but in case of objects you can still be able to modify the property of objects.
Some rules accompanying a constant variable:
a.) Must be declared using const keyword
b.) Must be initialized at time of declaration
c.) Cannot change value of const once assigned
Let’s try to understand with examples
<script type="text/javascript"> const message="This is some message"; //message = "This is not allowed"; const someObj = {id:1 , name :"test"}; //This is not allowed //someObj = {id:2 , name :"test"}; //This is allowed someObj.id =2; console.log(someObj.id); </script>
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
Constant variable also has blocked scope just like let keyword explained in previous articles.
<script type="text/javascript"> function testContantScope(index){ if (index == 1){ const somedata = "this is a test"; console.log(somedata); } console.log(somedata); } testContantScope(10); </script>
Outputs:
this is a test
SCRIPT5009: ‘somedata’ is undefined