“Using Array Const in JavaScript: Immutable Variables”

JavaScript Guide

JavaScript is a programming language widely used in modern web development. The const keyword, introduced with ES6 (ECMAScript 2015), is used to indicate that the values of variables cannot be reassigned. However, a constant array declared with const does not mean that the elements within the array are immutable. In this article, we’ll explain how arrays declared with const in JavaScript work and how their contents can still be modified.

What Is Array Const?

When you declare a variable in JavaScript using the const keyword, it means the variable’s value cannot be reassigned. However, when an array is defined using const, it signifies that the array reference itself is immutable, meaning you cannot reassign the array. Nonetheless, the contents of the array can still be modified.

const myArray = [1, 2, 3];
myArray[0] = 5; // Valid
console.log(myArray); // [5, 2, 3]

In the example above, an array named myArray is declared with const. Later, the first element of the array is updated to 5. This update is successful because const ensures the array reference is immutable, but the values of the elements within the array can still be changed.

Using Array Const

Array constants are often used for datasets that do not change, such as fixed lists or predefined arrays. However, it is important to remember that the values of the elements within the array can still be modified.

const weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
weekdays.push("Saturday", "Sunday");
console.log(weekdays); // ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

In the example above, the weekdays array, defined with const, has weekend days added to it. This operation is successful because const ensures the array reference is immutable, but the elements within the array can still be altered.

Conclusion

In JavaScript, an array declared with the const keyword indicates that the array reference is immutable, but the values of its elements can still be changed. Therefore, an array defined with const behaves like a fixed dataset and can be used for immutable values.

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir