How can we freeze the value in javascript?

A frozen object can no longer be changed. Freezing an object prevents:

  • New properties from being added to the object.
  • Existing properties to be removed from the object.
  • Changing the enumerability, configurability, or writability of existing properties.
  • Changing values of the existing object properties and prototype.

The syntax of the freeze() method is:

Object.freeze(obj)

The freeze() method, being a static method, is called using the Object class name.


freeze() Parameters

The freeze() method takes in:

  • obj - The object to freeze.

Return value from freeze()

  • The object that was passed to the function.

Notes:

  • Any attempts to add or remove from properties set of frozen objects will fail either silently or throw TypeError (mostly when in strict mode).
  • Objects sealed with Object.seal() can have their existing properties changed while Object.freeze() makes the existing properties immutable.


Example: Using freeze()

let obj = {
  prop: function () {},
  foo: "bar",
};

let o = Object.freeze(obj);

console.log(o == obj); // True -> Returns the same object
console.log(Object.isFrozen(obj)); // true

// changes will fail silently
obj.foo = "bar1";
console.log(obj.foo); // bar

// does not add silently
obj.new_foo = "bar";
console.log(obj.new_foo); // undefined

// Following will also throw error
// Object.setPrototypeOf(obj, { x: 20 })

Output

true
true
bar
undefined

Note: Object.freeze(obj) only applies to the immediate properties of obj. If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value reassignment operations.


Recommended Reading: JavaScript Object seal()

A video walkthrough of this article is available below.

ES6 introduced let and const for declaring variables. When you declare a variable using const you can’t then reassign the variable as is shown in the examples below.

const aValue = 1;
aValue = 2;
//Returns ---> Uncaught TypeError: Assignment to constant variable.
at :1:3

In the above example we declare a variable called aValue using const and we assign the value 1. Next, we try to reassign the value 2 to the variable and a typeError is thrown.

const ourObject = {
animalOne: "Cat",
animalTwo: "Dog",
animalThree: "Sheep"
};

ourObject = {}
VM178:1 Uncaught TypeError: Assignment to constant variable.
at :1:4

We try to do this again but this time using an object called ourObject and we hit the same error.

When we use the term mutable we are describing that something can be changed. Objects in JavaScript ( this includes objects, arrays and functions) which are assigned to a variable using const are mutable. It’s important to understand this because using const only stops the variable name (the identifier) from being reassigned not the object itself. If we wanted to change the animalOne property to be a cow we can do the following:

const ourObject = {
animalOne: "Cat",
animalTwo: "Dog",
animalThree: "Sheep"
};
ourObject.animalOne = "Cow";console.log(ourObject);
//Returns --->
// {animalOne: 'Cow', animalTwo: 'Dog', animalThree: 'Sheep'}

To be clear this would not work with one of the primitive data types such as strings (which are immutable). As the example below shows:

const ourString = "Hi";
ourString[1] = "o";
console.log(ourString);
//Returns ---> 'Hi'

To summarise you can change or mutate the object itself but you cannot change the name or identifier of the variable in which the object is stored. This is like saying you can change the decoration of your house but you can’t change your address.

How do we stop mutating objects?

We have clarified that you can’t stop the data inside a. object from being mutated just by using const. You can use a method provided by JavaScript called freeze. This method is part of the Object standard build in object. Once you have used this function you will not be able to change the object and if you are running your code using strict mode an error will be thrown. The return value of the function will be the object which was passed into the function. The syntax for this function is as follows:

Object.freeze(objectname);

Let’s try this function on ourObject.

const ourObject = {
animalOne: "Cat",
animalTwo: "Dog",
animalThree: "Sheep"
};
Object.freeze(ourObject);/*
Returns --->
const ourObject = { animalOne: "Cat",
animalTwo: "Dog",
animalThree: "Sheep"
};
*/
ourObject.animalOne = "Cow";console.log(ourObject);/*
Returns --->
const ourObject = { animalOne: "Cat",
animalTwo: "Dog",
animalThree: "Sheep"
};
*/

In the above example we declare the variable ourObject and assign an object with three properties, animalOne, animalTwo and animalThree. We then go ahead and freeze the object which returns the ourObject. When we then try to change the first property value to be the string cow and console.log the object. Nothing has changed and the original object is returned.

You could also use this on a array (arrays are a type of object) you didn’t want to change as is shown in the example below:

const ourArray = [1, 2, 3];
Object.freeze(ourArray);
//Returns ---> [1, 2, 3]ourArray[0] = 100;console.log(ourArray);
//Returns ---> [1, 2, 3]

I hope you enjoyed this article, please feel free to post any comments, questions, or feedback and follow me for more content!

How do you freeze a value in JavaScript?

Object.freeze() Method freeze() which is used to freeze an object. Freezing an object does not allow new properties to be added to an object and prevents from removing or altering the existing properties. Object. freeze() preserves the enumerability, configurability, writability and the prototype of the object.

How do you freeze an array in JavaScript?

You Can Freeze an Array, Too In JavaScript, Arrays are objects under the hood. So you can also apply Object. freeze() to arrays to make them immutable.

How do you lock an object in JavaScript?

There are many ways to lock an object according to your needs..
Object.freeze().
Object.seal().
Object.preventExtensions().

How do you deep freeze an object in JavaScript?

We can use an Object. freeze() method provided by JavaScript to prevent the addition of new properties with updating and deleting of existing properties.