DEV Community

Cover image for JavaScript Const re-assignment in Array with full Concepts
Sayyed Asad Ullah
Sayyed Asad Ullah

Posted on • Updated on

JavaScript Const re-assignment in Array with full Concepts

Variable Const

As we know that the "const" keyword was included in ES6(2016). The const variable cannot be reassign the value. JavaScript const variables must be assigned a value when they are declared like this...

const firstName = "Sayyed Asad";
Enter fullscreen mode Exit fullscreen mode

But this is a general rule, always declare a variable with const unless you know that the value will change.
Use const when you declare...

  1. New Array
  2. New Object
  3. New Function
  4. New Regexp

How would be re-assignment of const in an array and what's the reason about that behind the concept of this topic?

const developers = ['Sayyed Asad', 'Nisar', 'Toqeer'];
developers[2] = 'Jonas';


Enter fullscreen mode Exit fullscreen mode

Image description

So, first of all as a good experience in the JavaScript. I should be inform you here is const is manipulate. But I was still able to change one element of the Array here from Toqeer to Jonas.That is only primitive value. But an Array is not a primitive value. And so we can actually always change it so we can mutate it.

_

If you have some knowledge from my article. So, please follow me and share this post and like and comment on bellow this post.

_

Top comments (2)

Collapse
 
_genjudev profile image
Larson

const is just working as expected.

const arr = [1,2,3]
arr = [0] // Uncaught TypeError: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

you don't re-assign in your example. You updated an item.

Collapse
 
sayyedasad786 profile image
Sayyed Asad Ullah

Dear Lars Feldeisen please check the full code in your code and use array using with re-assignment of an array. This is very simple or critical topic for you and I suggest you please discuss this article with your seniors.