How to Declare Constants in JavaScript

In software development, there are certain values that we want to remain unchanged throughout the code execution.

These values are referred to as constants and are an essential aspect of programming.

In JavaScript, constants are declared using the keyword “const”.

This Javascript tutorial will provide a comprehensive guide on declaring constants in JavaScript with relevant code examples.


What are Constants in JavaScript?

Constants are values that can’t be reassigned or changed during the code execution.

They are declared using the keyword “const”.

For example, if we declare a constant “PI” with a value of 3.14, its value can’t be changed during the code execution.

This makes constants an ideal choice for values that we don’t want to be modified accidentally.

Declaring a Constant

Declaring a constant in JavaScript is simple. Here’s the syntax for declaring a constant:

const constantName = value;

For example, if we want to declare a constant for the value of Pi, we can do so like this:

const PI = 3.14;

It is important to note that once a constant is declared, its value can’t be changed during the code execution.

Attempting to do so will result in a TypeError.

Constants with Objects

In JavaScript, constants can be declared with objects.

However, unlike primitive data types, objects declared as constants can have their properties changed.

For example:

const person = { name: "John Doe" }; person.name = "Jane Doe"; // This is allowed

In this example, we declared an object “person” with a property “name”.

Although the object is declared as a constant, we can still change its properties.

Constants with Arrays

Similar to objects, arrays declared as constants can also have their elements modified.

For example:

const numbers = [1, 2, 3]; numbers.push(4); // This is allowed

In this example, we declared an array “numbers” as a constant.

Although the array is declared as a constant, we can still modify its elements.


Conclusion

Constants play an important role in software development, especially when we want to ensure that certain values remain unchanged during the code execution.

Declaring constants in JavaScript is simple and straightforward.

This tutorial provides a comprehensive guide on declaring constants in JavaScript, including code examples for objects and arrays.

Remember, once a constant is declared, its value can’t be changed during the code execution.