JavaScript const variable value change
As you known, Variable declare with const keyword you can not change later in program, but this condition is apply only for constant primitive values not for constant object or array.
Note : If you declare constant object or array value with const keyword, You can change or add the properties of const variables.
Let's see the examples:
➤ Example 1 : constant primitive values;
If we assign a primitive value to a constant, we can't change the primitive value.
- <script>
const x = 25;//output : 25
x++; //ERROR, not allowed
x = 20; //ERROR, not allowed
x = x+5; //ERROR, not allowed
- </script>
# Let see how to change the value of const variable
➤ Example 2: constant objects values;
You can change the properties of a constant object.
- <script>
//You can create a const object.
const student = {name:"Ankaj", branch:"CS"};
//You can change a property.
student.name = "Ankaj Gupta"; //Allow
//You can add a property.
student.rollno = "45"; //Allow
//Note : But you can't re-assign a constant object.
student = {name:"Anmol", branch:"initialize"}; //ERROR, not allowed
- </script>
➤ Example 3 : constant array values;
You can change the elements of a constant array.
- <script>
//You can create a const array.
const student = ["Name", "Branch", "Rollno"];
//You can change an element.
student[2] = "Enroll_No"; //Allow
//You can add an element.
student.push("Gender"); //Allow
//Note : But you can't reassign a constant array.
student = ["Name", "Branch", "Enroll_No", "Gender"];//ERROR, not allowed
- </script>
Comments