A variable created using the ‘const’ keyword won’t welcome any re-assignment(s). And in-turn it will throw an error if it is tried to be re-assigned with a new value. Unlike ‘let’ and ‘var’, a const variable should strictly be declared and defined in the same single code statement. To be clear on this, the declaration is the process of assigning a memory block to a variable. And initialisation involves filling that memory block with a value. This value can be anything from a string or number or boolean to a function definition.
Further, a const variable is scoped to a block. This means that a const variable can only be accessed in the block it is declared in, in the program. The scope of a const variable is exactly the same as that of a ‘let’ variable. Similarly, const variables’ hoisting is the same as let variable hoisting. So, apart from the re-assignment part, there is no difference between a ‘let’ variable and a ‘const’ variable.
Let’s see an example:
In the above example, note that there are three blocks in the script tag. Now, similar to a ‘let’ variable, a ‘const’ variable is accessible only in the block it is declared and initialised in. So, the output of the above code will be as follows:
Now, it’s clear that a const variable can not be re-assigned with a value. But this doesn’t really make it completely immutable.
If the ‘const’ variable holds a string or numeric or boolean or a null value, it is perfectly immutable. It can not be assigned a new value and its existing value is also unmodifiable.
But if the ‘const’ variable holds an object, the object data can surely be modified. Note that the object is actually a reference and it actually refers to its data. So, the data inside the object can be modified even when the object is created using const. But, the object itself can not change i.e. the ‘const’ variable can not point to a different object. And this object can not be renamed as well.
Free money-back guarantee
Unlimited access to all platform courses
100's of practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Sharing is caring
Did you like what Aditya Prashant Tekale, Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, wrote? Thank them for their work by sharing it on social media.
- Aditya Prashant Tekale
- Agam singh
- Aman Ahmed Siddiqui
- Aman Chopra
- Amol Shelke
- Anas Khan
- Anirudh Panda
- Ankur Balwada
- Anshul Soni