Why You Can Change Properties of a const Object in JavaScript. JavaScript const Keyword. const Object Property Updates Explained with Example. const Does not Mean Constant JavaScript Object Mutability Explained Clearly

Why You Can Change Properties of a const Object in JavaScript. JavaScript const Keyword. const Object Property Updates Explained with Example. const Does not Mean Constant JavaScript Object Mutability Explained Clearly

Lets explain the Code:

const obj = { a: 1 };
obj.a = 2; console.log(obj);

Step 1: Declare the Object

const obj = { a: 1 };
  • const Keyword:

    • In JavaScript, const means the reference to the variable cannot be changed.
    • But it does not make the object immutable.
    • You can still change the properties inside the object.
  • What is Happening Here?
    • You are declaring a constant variable named obj.
    • You are assigning it an object with one property:

{
a: 1
}
    • This creates a reference in memory pointing to that object.

Step 2: Modify the Property

obj.a = 2;
  • You are not changing the reference to the object.
  • You are just modifying the value of property a inside the same object.
  • This is allowed even though the object was declared with const.

Important:

  • If you try to reassign the whole object like this:

obj = { a: 10 }; // ❌ This will throw an error.

This is not allowed because you cannot change the reference of a const variable.

  • But updating existing properties:
obj.a = 2; // ✅ This is allowed.

This is completely valid.


Step 3: Log the Object

console.log(obj);
  • This will print the current state of the object to the console.
  • Output:

{ a: 2 }

Why This Works:

  • In JavaScript, const only freezes the binding (the link between the variable and the object), not the object’s contents.
  • Objects in JavaScript are mutable by default.
  • If you want to make the object truly immutable, you would have to use:

Object.freeze(obj);

But even that only works at the top level (it’s shallow).


Quick Summary:

StepActionResult
1Declare const obj = {a: 1}Creates an object, reference is constant
2Modify obj.a = 2Changes the property value inside the same object
3Log the objectPrints { a: 2 }

Key Takeaways:

  • const prevents reassignment, not mutation.
  • Objects declared with const can still have their properties changed.
  • If you want an object that cannot be changed, you must use Object.freeze.

✔ Final Answer:

D) { a: 2 }

This question appeared in the Deloitte 2nd round of interview, testing the candidate’s knowledge of const keyword with object in JavaScript.

Post a Comment

Previous Post Next Post