Every Javascript developer knows that var and let is reassignable but const cannot be reassigned or redeclared again.
But there is a little secret about const, let's look at some code.
const val = 10; // 10
val = 15; // Uncaught TypeError: Assignment to constant variable
As expected, we are unable to reassign val to another number. How about string?
const str = 'I am a String'; // 'I am a String'
str = 'I am a Cheese Stringers now'; // Uncaught TypeError: Assignment to constant variable
Still no. How about the array and object?
// Array
const arrVariable = [10, 11, 12, 13]; // [10, 11, 12, 13]
arrVariable = [14, 15, 16]; // Uncaught TypeError: Assignment to constant variable
// Obj
const objVariable = {1: 10, 2: 20, 3: 30, 4: 40}; // {1: 10, 2: 20, 3: 30, 4: 40}
objVariable = {5: 50, 6: 60}; // Uncaught TypeError: Assignment to constant variable
Javascript: Nope nope nope you can't do that nope...
But what if we do this:
const arrVariable = [10, 11, 12, 13]; // [10, 11, 12, 13]
arrVariable.push(14); // [10, 11, 12, 13, 14]
What?! Let's continue and play around a bit...
arrVariable[0] = 'Eat'; // ['Eat', 11, 12, 13, 14]
arrVariable[1] = 'π₯'; // ['Eat', 'π₯', 12, 13, 14]
arrVariable[2] = {1: 'Avocado'}; // ['Eat', 'π₯', {1: 'Avocado'}, 13, 14]
arrVariable[3] = true; // ['Eat', 'π₯', {1: 'Avocado'}, true, 14]
OMG what just happened?
From MDN Web Docs, it describes:
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
Who is the variable identifier/constant here? arrVariable, not the array itself.
MDN said variable identifier/constant cannot be reassigned, which means arrVariable cannot be reassigned. But what about the array? It doesn't have any effect, of course, it is still mutable.
const tells the reader that your variable cannot be reassigned, which is why it is highly recommended to use. It prevents us to create some unnecessary bugs and improve code readability.
Similar to object:
const objVariable = {1: 10, 2: 20, 3: 30, 4: 40}; // {1: 10, 2: 20, 3: 30, 4: 40}
objVariable[1] = 'π'; // {1: 'π', 2: 20, 3: 30, 4: 40}
objVariable[2] = ['Pizza', 'is', 'life']; // {1: 'π', 2: ['Pizza', 'is', 'life'], 3: 30, 4: 40}
objVariable[3] = true; // {1: 'π', 2: ['Pizza', 'is', 'life'], 3: true, 4: 40}
objVariable[5] = {1: 'πΊ', 2: 'π'} // {1: 'π', 2: ['Pizza', 'is', 'life'], 3: true, 4: 40, 5: {1: 'πΊ', 2: 'π'}
So next time if someone asks you about our friend const, you know what to say.
Lastly,
arrVariable = 'I am an π₯'; // Uncaught TypeError: Assignment to constant variable
πππππ
Still nope, anyway...
Top comments (1)
Good one. enjoyed it