Question

How to freeze a JavaScript array?

Answer and Explanation

To freeze a JavaScript array, preventing modifications such as adding, removing, or changing elements, you can use the Object.freeze() method. This method makes the array immutable.

Here's a step-by-step explanation:

1. Declare an array:

- First, you need to have the array you wish to freeze.

  let myArray = [1, 2, 3, 4, 5];

2. Use Object.freeze():

- Apply the Object.freeze() method to your array. This will prevent any changes to the array.

  Object.freeze(myArray);

3. Understanding the Effects of Freezing:

- After freezing, you will not be able to:

- Add new elements using push(), unshift(), etc.

- Remove existing elements using pop(), shift(), splice(), etc.

- Change the value of existing elements with direct assignment myArray[0] = 10.

4. Trying to Modify a Frozen Array:

- If you try to modify the frozen array, JavaScript will throw an error in strict mode ('use strict';) or silently fail in non-strict mode.

5. Example Code:

  "use strict";
  let myArray = [1, 2, 3, 4, 5];
  Object.freeze(myArray);
  // Attempting to add a new element
  try {
    myArray.push(6); // This will throw an error
  }
  catch (error){
   console.error("Error:", error);
  }
  // Attempting to modify an existing element
  try {
   myArray[0] = 10; // This will also throw an error
  }
  catch (error){
   console.error("Error:", error);
  }
  console.log(myArray); // Output: [1, 2, 3, 4, 5] (unchanged)

6. Important Considerations:

- Object.freeze() only performs a shallow freeze. If an array contains objects, those objects will not be frozen. You'll have to recursively freeze those objects if you need deep immutability.

By using Object.freeze(), you can create immutable arrays in JavaScript, which can be especially helpful in scenarios where you need to ensure data consistency and prevent unintended modifications. Remember, it is a shallow freeze, so it won't affect the content of objects within the array.

More questions