DEV Community

avinash-repo
avinash-repo

Posted on

Const Vs freeze for Object

It appears there is a small typo in your question. Assuming you meant const object1 vs Object.freeze(object1), I'll provide a simple example to illustrate the difference:

const object1:

const object1 = {
  key: 'value',
};

// Modifying a property is allowed
object1.key = 'new value'; //yhaan pe const hote huye bhi value ressign ho gyee

console.log(object1); // { key: 'new value' }
Enter fullscreen mode Exit fullscreen mode

In this example, object1 is declared using const, making the variable itself immutable. However, the properties of the object are not immutable, and you can still modify them.

Object.freeze(object1):

const object2 = {
  key: 'value',
};

Object.freeze(object2);

// Modifying a property is not allowed; it has no effect
object2.key = 'new value';

console.log(object2); // { key: 'value' }
Enter fullscreen mode Exit fullscreen mode

In this example, Object.freeze(object2) is used to freeze the entire object. This prevents any modifications to the object, making both the variable and its properties immutable. Attempting to modify a property after freezing has no effect.

In summary:

  • Using const on an object variable makes the variable itself immutable, but the properties can still be modified.
  • Object.freeze() ensures immutability for both the object variable and its properties.

Certainly, let's consider a more comprehensive example using const and Object.freeze() to showcase their impact on immutability:

Using const:

const personConst = {
  name: 'John',
  age: 30,
};

// Modifying a property is allowed
personConst.age = 31;

console.log(personConst); // { name: 'John', age: 31 }
Enter fullscreen mode Exit fullscreen mode

In this example, even though personConst is declared with const, the properties within the object (name and age) can still be modified. The immutability enforced by const applies to the variable itself, not its content.

Using Object.freeze():

const personFreeze = Object.freeze({
  name: 'Jane',
  age: 25,
});

// Attempting to modify a property has no effect
personFreeze.age = 26;
personFreeze.address = '123 Main St'; // Attempting to add a new property has no effect

//yhaan pe const hote huye bhi value ressign nhi huyee

console.log(personFreeze); // { name: 'Jane', age: 25 }
Enter fullscreen mode Exit fullscreen mode

In this example, Object.freeze() is applied to personFreeze. As a result, attempting to modify existing properties (age) or add new properties (address) has no effect. The entire object is frozen, ensuring immutability.

This demonstrates that while const provides a level of immutability for the variable itself, Object.freeze() goes further by preventing modifications to the object's properties as well. For scenarios requiring a high degree of immutability, especially for objects with constant values, Object.freeze() is a more suitable choice.

Certainly, let's explore how const behaves when used with arrays containing multiple child arrays:

Using const with Nested Arrays:

const nestedArrayConst = [
  [1, 2, 3],
  ['a', 'b', 'c'],
];

// Modifying a property (nested array) is allowed
nestedArrayConst[0][1] = 99;

console.log(nestedArrayConst); // [[1, 99, 3], ['a', 'b', 'c']]
Enter fullscreen mode Exit fullscreen mode

In this example, nestedArrayConst is declared with const, and it contains two child arrays. Even though the variable itself is immutable, modifications to the content of the nested arrays are allowed. In this case, the value at index [0][1] is changed from 2 to 99.

This behavior occurs because const applies to the variable reference, not the contents it points to. As a result, you can modify properties (elements) within the array, including those that are arrays themselves.

If you want to achieve a higher level of immutability for the entire structure, including nested arrays, you would need to use other techniques like deep freezing:

Deep Freezing Nested Arrays:

const deepFreeze = (obj) => {
  Object.freeze(obj);
  if (obj instanceof Array) {
    for (const prop of obj) {
      deepFreeze(prop);
    }
  }
};

const nestedArrayFreeze = [
  [1, 2, 3],
  ['a', 'b', 'c'],
];

deepFreeze(nestedArrayFreeze);

// Attempting to modify a property (nested array) has no effect
nestedArrayFreeze[0][1] = 99;

console.log(nestedArrayFreeze); // [[1, 2, 3], ['a', 'b', 'c']]
Enter fullscreen mode Exit fullscreen mode

In this example, a deepFreeze function is applied to nestedArrayFreeze, ensuring that both the outer array and all nested arrays are frozen. Attempting to modify any property within the structure has no effect.

In summary, while const provides immutability for the variable reference, it doesn't prevent modifications to the content of arrays, including nested arrays. If you need full immutability for the entire structure, including nested arrays, additional measures such as deep freezing are required.

Certainly, an alternate way to achieve a deep freeze for arrays is by using a recursive function. Here's an example of a function that recursively freezes both the outer array and any nested arrays:

const deepFreezeArray = (array) => {
  Object.freeze(array); // Freeze the outer array

  // Iterate through each element
  for (const element of array) {
    if (Array.isArray(element)) {
      // Recursively freeze nested arrays
      deepFreezeArray(element);
    }
  }
};

const nestedArray = [
  [1, 2, 3],
  ['a', 'b', 'c'],
  { objKey: 'value' }, // Objects within the array
];

deepFreezeArray(nestedArray);

// Attempting to modify any property has no effect
nestedArray[0][1] = 99;
nestedArray[2].objKey = 'new value';

console.log(nestedArray); // [[1, 2, 3], ['a', 'b', 'c'], { objKey: 'value' }]
Enter fullscreen mode Exit fullscreen mode

In this example, the deepFreezeArray function recursively freezes the outer array and all nested arrays within it. Note that if there are objects within the array, they won't be frozen by this function. If you also need to freeze objects, a more comprehensive deep freezing function would be necessary.

This approach ensures that modifications to the content of both the outer array and any nested arrays are prevented, providing a higher level of immutability.

Certainly, let's compare the behaviors of using const, Object.freeze(), and Set with a simple example involving an array of objects:

Using const:

const arrayConst = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
];

// Modifying a property within an object is allowed
arrayConst[0].name = 'Johnny';

console.log(arrayConst); // [{ id: 1, name: 'Johnny' }, { id: 2, name: 'Jane' }]
Enter fullscreen mode Exit fullscreen mode

In this example, although the array itself is declared with const, modifications to the properties of objects within the array are allowed. The immutability enforced by const applies to the variable reference but not the content of the array.

Using Object.freeze():

const arrayFreeze = Object.freeze([
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
]);

// Attempting to modify a property within an object has no effect
arrayFreeze[0].name = 'Johnny';

console.log(arrayFreeze); // [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
Enter fullscreen mode Exit fullscreen mode

In this example, the entire array is frozen using Object.freeze(). As a result, attempting to modify any property within the objects has no effect. The entire structure, including the array and its objects, is immutable.

Using Set:

const arraySet = new Set([
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
]);

// Adding a new object to the Set
arraySet.add({ id: 3, name: 'Alice' });

console.log(arraySet); // Set { { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Alice' } }
Enter fullscreen mode Exit fullscreen mode

In this example, a Set is used to store objects. Unlike arrays, Sets automatically enforce uniqueness, so adding a new object with the same properties as an existing one will not result in a duplicate. However, Set does not prevent modifications to the existing objects within it.

In summary:

  • const provides immutability for the variable reference but allows modifications to the content of the array.
  • Object.freeze() ensures immutability for both the array and its objects.
  • Set ensures uniqueness of elements but does not prevent modifications to the objects within it.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

AI generated/assisted posts - like this one - should try to adhere to the guidelines for such content.