Explain the difference between Object.freeze() vs const
Explain the difference between Object.freeze() vs const
The difference between Object.freeze()
and const
in JavaScript pertains to the level and type of immutability they enforce.
const
is a keyword introduced in ES6 (ECMAScript 2015) that creates a read-only reference to a value. When you declare a variable with const
, you cannot reassign it to a different value. However, if the value assigned to a const
variable is an object, you can still modify the properties of that object, even though you cannot reassign the variable itself to a different object[3].
Here's an example demonstrating const
with an object:
const car = { color: "red" };
car.color = "blue"; // This is allowed.
car = { color: "green" }; // This will throw a TypeError because reassignment is not allowed.
On the other hand, Object.freeze()
is a method that makes an object immutable. When you freeze an object, you can no longer add new properties to it, delete existing properties, or change the enumerability, configurability, writability, or value of its properties. The object's prototype also cannot be reassigned. However, Object.freeze()
is shallow, meaning that it only affects the immediate properties of the object. If the object has properties that ar...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào