Skip to content

Commit 0cc4269

Browse files
committed
feat: Add question 478 about const vs Object.freeze
1 parent d24cf5c commit 0cc4269

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9552,6 +9552,37 @@ Common use cases and benefits:
95529552

95539553
**[⬆ Back to Top](#table-of-contents)**
95549554

9555+
478. ### What is the difference between const and Object.freeze
9556+
9557+
The main difference is that `const` applies to **variables** (bindings), while `Object.freeze()` applies to **values** (objects).
9558+
9559+
1. **`const`**: Prevents the reassignment of a variable identifier. It ensures that the variable name always points to the same memory reference. However, if the variable holds an object or array, the *contents* of that object can still be modified.
9560+
2. **`Object.freeze()`**: Prevents the modification of an object's properties. It makes the object immutable (you cannot add, remove, or change properties), but it does not affect the variable assignment itself (unless the variable is also declared with `const`).
9561+
9562+
**Example:**
9563+
9564+
```javascript
9565+
// Case 1: Using const (Reassignment prevented, Mutation allowed)
9566+
const person = { name: "John" };
9567+
person.name = "Doe"; // ✅ Allowed: The object is mutable
9568+
console.log(person.name); // "Doe"
9569+
9570+
// person = { name: "Jane" }; // ❌ Error: Assignment to constant variable
9571+
9572+
// Case 2: Using Object.freeze (Reassignment allowed, Mutation prevented)
9573+
let profile = { name: "John" };
9574+
Object.freeze(profile);
9575+
9576+
profile.name = "Doe"; // ❌ Ignored (or throws TypeError in strict mode)
9577+
console.log(profile.name); // "John"
9578+
9579+
profile = { name: "Jane" }; // ✅ Allowed: 'profile' is declared with 'let'
9580+
console.log(profile.name); // "Jane"
9581+
9582+
9583+
**[⬆ Back to Top](#table-of-contents)**
9584+
9585+
95559586
<!-- QUESTIONS_END -->
95569587
### Coding Exercise
95579588

0 commit comments

Comments
 (0)