Sobes.tech
Junior

What does the freeze method do in JavaScript?

sobes.tech AI

Answer from AI

The Object.freeze() method freezes an object, preventing new properties from being added, existing properties from being removed, and existing property values from being changed. It also prevents the object's prototype from being altered. A frozen object remains immutable.

Applying Object.freeze():

  1. Creating constant objects: Ensures that the object will not be modified in subsequent code.
  2. Performance improvement: Some JavaScript engines find it easier to optimize access to immutable objects.
  3. Security: Protects the internal data of the object from accidental or malicious modifications.

Important note: Object.freeze() only performs a shallow freeze. If the object has properties that reference other objects, those nested objects can be modified unless they are also frozen.

Example:

const obj = {
  prop1: 42,
  prop2: {
    nestedProp: 'hello'
  }
};

Object.freeze(obj);

// Attempts to modify will be ignored in "strict mode"
// In non-strict mode, they may not throw an error, but changes will not occur
obj.prop1 = 100; // Will not change
delete obj.prop1; // Will not delete
obj.newProp = 'world'; // Will not add

console.log(obj.prop1); // 42
console.log(obj.newProp); // undefined

// Nested object IS NOT frozen
obj.prop2.nestedProp = 'goodbye'; // Will change
console.log(obj.prop2.nestedProp); // goodbye