Why is this returning true if Let should be mutable and Const should be immutable?

let flag1 = false;
const myObj = {
  flag1: true 
};
function updateValue (flg1, obj) {
  flg1 = true;
  obj.flag1 = false;
}
 
updateValue(flag1, myObj);
console.log(flag1 == myObj.flag1);

A variable declared with the keyword const can be mutable, if the type of data it is storing is mutable. Objects (like you’ve created with const myObj), are mutable, which means their properties can be altered, but the variable’s type cannot be changed. For example, this throws an error because I’m trying to change the variable’s type:

const someObj = {
  someProperty: false
};
someObj = "hello, world!";

Beware that it isn’t just changing the type of constants which cause errors. Any reassignment of a constant will throw an error:

const someArr = [1, 2, 3];
someArr = [4, 5, 6];
//that will throw an error, as you're reassigning a constant
const someOtherArr = [4, 3, 2];
someOtherArr.push(5);//someOtherArr is now [4, 3, 2, 5]
//that didn't throw an error, as you're not reassigning someOtherArr

Here is a good article on mutability vs reassignment.

I hope this helps!

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.