I'm proudly teaching myself coding, on the journey so far, here is what I think I didn't know about const variable declaration
(1) Const declaration in JavaScript is that type of variable declaration in which its ''variable assignment'' is set to read-only. This means, value of variable can't be changed once it has been declared at the declaration time.
Using the code below to drive home my explanation
const a = 2;
console.log(a) //2
a = 2;//typeError
In line 3 of the snippet above, assigning the variable to another value didn't work. With const, you can't change the value of variable once it's declared.
(2) Unlike var and let, to get a const declaration with an "undefined" value, you have to declare it manually, const a = undefined
Consider the code below:
var a; //undefined
let b; //undefined
const c; //missing initialisation in const declaration
now we declare it manually
const c = undefined;
console.log(c) //undefined
Now from the above example shown so far, should I think declaring a variable with const restricts the value of the variable itself? Well, this could have been my assumption, if I didn't read further. The answer, however, is simply No!
Const is not a restriction on the value itself but on the variable assignment of the value. This means that the value of const can be modified. Only the variable assignment of the value is frozen, and can't be modified.
Consider the code below
const a = [1,2,3];
a.push(4);
console.log(a)//[1,2,3,4]
Wow, the value could be modified, and not read-only. Now what exactly do I mean by variable assignment of a const is immutable/frozen. Let's revisit our snippet above
const a = [1,2,3];
a.push(4)
console.log(a)//[1,2,3,4] as expected
//now assigning a variable to a new value
a = 2; //typeError!
Reassigning a to 42 didn't work simply because the variable assignment of const is frozen. Finally, we can say that the value of const itself is mutable but the variable, a reference to the value is immutable.
I'm excited about my journey so far and this is my first publication on this platform
Top comments (2)
thanks for the informations
My pleasure