Analyzing the const feature in JavaScript

javascript const feature overview
10 November 2024

In the world of JavaScript programming, one of the concepts that may be confusing is the use of const for defining variables. In this article, we will delve into and explain this concept. Join us as we explore the simple way and relevant examples to remember the correct use of const.

In JavaScript, when you want to define a constant value that does not change during the execution of the program, the key term const is used. One common misconception is that some may think const should never change, but the truth is that if your variable is an object or array, you can change its properties; however, you cannot assign a new value to the variable itself.

Another point to consider is that the variables defined with const must hold the same initial value; hence, you cannot redefine a const variable without an initial value.

Consider a scenario where you need a specific value like a URL for an API that the program will require in different places. In this case, using const is appropriate, as it ensures that the URL value will not change over time.

Now, let’s look at some examples to better understand the concept of const. In these examples, we will demonstrate how you can work with const.


// Define a constant variable
const pi = 3.14159;

// Use const to define an object
const person = {
    name: 'Ali',
    age: 30
};

// Change a property of the object
person.age = 31;

// Define an array with const
const colors = ['Red', 'Green', 'Blue'];

// Add a new value to the array
colors.push('Yellow');

Now, let’s explain the comments in this code:

// Define a constant variable
Here, the pi value is defined as a constant with a numeric value indicating that pi is a constant.

// Use const to define an object
Here, a person object is defined with properties name and age.

// Change a property of the object
We can change the properties of the person object even if it’s defined with const.

// Define an array with const
Here, an array colors is defined, where we can change its elements.

// Add a new value to the array
In this part, a new value 'Yellow' is added to the colors array.

FAQ

?

Can I change the value of a constant variable or array?

?

Why should we use const?