DEV Community

coyla
coyla

Posted on

Misunderstanding of const keyword in JS

When you read forums or ask to JS friends developers about what's const keyword, sometimes they use this kind of answer:

variable const cannot be changed" or "const cannot be updated"

I think they really understand the difference between const let and var, but this sentences can be wrongly interpreted.

We should use the word "reassigned" instead of "change/update"

🚫 Reassignment


const color = 'red';
color = 'blue';
// TypeError: Assignment to constant variable.
color = { 'hex': '#FF0000' };
// TypeError: Assignment to constant variable.

const profile = { 'firstname': '', 'lastname': '' };
profile = 'Name';
// TypeError: Assignment to constant variable.

We can't reassign, set a new value to color variable.

✅ Change/Update value

const profile = { 'firstname': '', 'lastname': '' };
profile.firstname = 'Naruto';
profile.lastname = 'Uzumaki';
profile.rank = 'Hokage';

// output 
{ firstname: 'Naruto', lastname: 'Uzumaki', rank: 'Hokage' };

So, we were able to add a new property rank and change profile's property values, that means, we have changed the value of profile object.

😖 Confusion

const color = 'red';
color = 'blue';
// TypeError: Assignment to constant variable.

Here if you are thinking you are changing the value 'red' to 'blue'. You can be confused and might be wondering "Why i've got the TypeError if i'm changing the string value"

'r' letter doesn't change to 'b', 'e' to 'l' and so on ... actually 'blue' is considered as a "NEW" string so in other words it's a reassignment. That's a property of primitive values, when you think these kind of values have changed actually they are new values.

String, numbers and booleans are part of primitive values, this kind of values are immutable, their value can't be changed.

I hope this explanation will help someone. Let me know your feelings

ps: my english is not perfect, so give me some feedbacks if you want

Top comments (0)