ES6 For Beginners : Using const keyword Declaration

Share on FacebookTweet about this on TwitterShare on Google+Share on RedditShare on StumbleUponDigg thisFlattr the authorPin on PinterestShare on TumblrShare on LinkedInPrint this pageBuffer this page

The const keyword as the name suggests is a great way to create constants in JavaScript with ES6. As we will see in the code snippets below the const keyword will give developers another tool to write more meaningful code easily.

Let’s dive right into the code, I will use more or less the same code that I used in the post about the let keyword.

Here we are declaring the variable pi as a constant with the const keyword, inside the if condition we are changing the value of the constant pi this will give us the following error.

ES6 const keyword error

 

This illustrates that we cannot change the value of any variable the is declared using the const keyword.

 

Protecting Objects with const

Const can also be use with object, let’s see how,

This will give us the same “invalid assignment” error as the const declaration will protect the object.

 

A thing to Note here is that the values inside the myObj object are not protected. Let’s see an example

As shown using the dot notation myObj.key1 we can change the values of the keys of the object.

 

Check out the entire list of ES6 tutorials and posts here.

 

Got A Question?

Hit me up in the comments here or on the comments section on my YouTube Channel or on twitter @pointDeveloper

 

 

Consider Subscribing / Donating
Subscribe To Mailing List
Donate
If my site was helpful to you, then please consider donating via paypal:

Prantik Vaghela (pointdeveloper)

Hi my name is Prantik Vaghela. I have done my Bachelors and Masters in Computer Science and am a web developer and now a Tutor through my blog. :-)

%d bloggers like this: