Understanding the const Keyword in Javascript
Whether you're new to JavaScript or an experienced developer, you've likely come across the const keyword. It's a way to declare variables that hold constant values. Once you've declared a variable using const a keyword, you cannot assign it a new value. This makes const it ideal for situations where you want to ensure the immutability of a variable throughout your code.
There are a lot of benefits of using the const keyword here are some of them:
Predictability: Variables declared with const cannot be reassigned, ensuring their value remains constant
const restricts variable scope to the block scope where they are declared
Let's understand with an example what happens when we re-assign values to a const variable.
const a = 10
console.log(a) //output : 10
a=15;
console.log(a) //output : TypeError: Assignment to constant variable.
But hey did I say that values declared with const
cannot be re-assigned? let's move further with our blog and understand why I chose to write "const is not constant". For this, we will see how const works with Arrays in js only then we will be able to understand this topic of mutability vs immutability
Data types in Javascript
Before moving Further We have to know that there are two types of Data in Js, Understanding these data types is fundamental to working with JavaScript, as they influence how values are stored, manipulated, and interact with each other.
Primitive Data-types: Number, String, Boolean, Null, Undefined, Symbol. If you know about these then well and good & if you don't, google them and read more about them.
Complex Data Types:
Object: Represents a collection of key-value pairs, where values can be of any data type, including functions and arrays.
Array: Represents an ordered collection of values, accessible by index.
Function: Represents a reusable block of code that can be invoked with specific parameters.
let's deep dive more to understand the assigning and re-assigning of the const variable
const a = 10;
a=15
console.log(a); // Output: assignment error:cannot assign values to const
b = a;
console.log(b); // Output: 10
b = 8;
console.log(b); // Output: 8
console.log(a); // Output: 10
Here's the breakdown of the code execution:
const a = 10;: Variable a is declared and assigned the value 10 using const. a is a constant variable, and its value cannot be re-assigned.
b = a;: The value of a (which is 10) is assigned to b. Since b is not explicitly declared using let or var, it becomes a global variable.
console.log(b);: The value of b is logged into the console, which is 10 (the initial value assigned from a).
b = 8;: The value of b is re-assigned to 8. As b is a global variable, in this case, it can be modified.
console.log(b);: The new value of b, which is 8, is logged to the console.
console.log(a);: The value a remains unchanged and is still 10. const ensures that a it cannot be re-assigned.
Now that we have understood this, we are ready to understand the const keyword with arrays but Before that we some interesting things to tackle
Understanding Redeclaration & Reassignment
We know that arrays in JavaScript are mutable, meaning their elements can be modified.
let arr =[5,58,9,6,3]
console.log(arr) //output: [ 5, 58, 9, 6, 3 ]
arr[1]=8
console.log(arr) //output: [ 5, 8, 9, 6, 3 ] This shows arrays are mutable
but what happens when we re-assign the value of the arr with new values using the Let declaration? let's see with code examples
//re-assigning primitve data types
let a =15
a=18
console.log(a) //output : 18
//re-assigning complex data types
let arr =[5,58,9,6,3]
console.log(arr) //output: [ 5, 58, 9, 6, 3 ]
arr=[8,6,96,53,12]
console.log(arr) //output: [ 8, 6, 96, 53, 12 ]
With the Let keyword let's understand these terms before moving forward
- Redeclaration: It means changing the memory location of the variable which will throw an error. Note: re-declaration will not throw an error in the case of using var
let s = 90
let s=89
console.log(s) //SyntaxError:Identifier 's' has already been declared
//using var keyword to redeclared
var a = 90
var a=89
console.log(a) //output : 89
- Re-assignment: It simply means changing the value of the variable without actually changing the memory allocation
//re-assignment using let and var
let s = 90
s=84
console.log(s) //output:84
//var
var a = 90
a=89
console.log(a) //output:89
Now that we have understood the difference between these terms let's look at what happens when we apply these with const in complex data types
Using the const keyword with arrays
const arr =[5,58,9,6,3]
console.log(arr)
arr=[8,6,96,53,12]
console.log(arr) //TypeError: Assignment to constant variable.
Why did this happen? As we know that once the array is declared with const a keyword it cannot be re-assigned even though we know that array is mutable. So does that means we cannot change the values of the arr if we use the const keyword?
let's look at another code to understand better
//const is immutable but array is not
const arr =[5,58,9,6,3]
arr[2]=10
console.log(arr) //output : [ 5, 58, 10, 6, 3 ]
what just happened here. isn't this code suppose to return an error? how can an array with a const declaration is changed/updated? The answer to this is that const is immutable & It defines a constant reference to an array.
If you know that complex data types are stored in a heap memory in the js engine. when you do something like this (given below). Both the variable are referencing the same array and so if you make changes to one the other one will also be affected:
let arr=[1,2,3]
abb=arr
abb.push(10)
console.log(abb) //output:[ 1, 2, 3, 10 ]
console.log(arr) //output:[ 1, 2, 3, 10 ]
but in the case of primitive data type when you do this same thing(given below) you will get a new variable and both the original and duplicate variable will have completely different reference
let a =10
let b= a
b= 18
console.log(b) //output:18
console.log(a) //output : 10
So when you do const arr =[1,2,3]
you are restricting the reference to this variable but you can still perform all the array methods but you cannot re-assign the complete new value to the const array:
const a =[1,2,3]
a.push(1,58) //pushed new valued at the end of a
a.pop() //removed the last value
console.log(a) //output :[ 1, 2, 3, 1 ]
Conclusion
So I hope now you would have understood "why an array declared using const can still be modified". Understanding these things will make you a good JS developer and these things will be asked in the interview. So make sure you revise these topics well before your interviews.
If you still have any doubts then you can use the comments section to ask your doubts. To understand JS from a more micro level I would recommend you a playlist called Namaste Javascript by Akshay Saini on Youtube he has some of the best js videos on the internet. Do check this playlist.
Thanks once again if you have read till here.
Connect with me on socials :
Top comments (0)