JavaScript const

You are Here:

JavaScript const

The const is a JavaScript keyword for defining variables that are prevented from being updated.

Note: The const does NOT define a constant value. It defines a constant reference to a value, i.e., we cannot change constant primitive values, but we can change the properties of constant objects.

Update const

Note: The following example will throw an error as we are trying to update the value which is declared with const keyword.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> const x = 1; x = x + 1; document.write("x = "+x); </script> </body> </html>

Re-Assign const

Note: The following example will throw an error as we are trying to re-assogm the value which is declared with const keyword.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> const x = 1; x = 1; document.write("x = "+x); </script> </body> </html>

Add / Change / Delete Property in Object const

Note: The following example will NOT throw an error as we are trying to change the properties of constant objects.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> const bike = {company:"Honda", model:"CBR 1000RR"}; //Add property bike.color="Red"; //Change property bike.model="Gold Wing"; //Delete property delete bike["company"]; document.write("I went to "+bike.company+" Showroom"); document.write("<br>I purchased "+bike.model); document.write("<br>Which is "+bike.color+" in color"); </script> </body> </html>

Trying to Re-Assign Object const

Note: The following example will throw an error as we are trying to change the object itself.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <script> const bike = {company:"Honda", model:"CBR 1000RR"}; bike = {company:"Harley Davidson", model:"Fat Bob"}; document.write("Company = "+bike.company); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author