JavaScript Basics: Object.freeze and Object.isFrozen

By @ghasemkiani2/10/2018javascript

In the previous posts, I discussed about two levels of object protection: Object.preventExtensions and Object.seal. The last level of protection is Object.freeze, which also makes all the properties unchangeable. You cannot add a new property, you cannot delete an existing property, you cannot reconfigure it, and you cannot change its value.

The following code snippet demonstrates the effects of Object.freeze:

	let myObj = {
		name: "Ali",
	};
	Object.freeze(myObj);
	
	console.log(Object.isFrozen(myObj)); // true

	// You cannot add new properties. This fails silently.
	myObj.age = 19;
	console.log(myObj.age); // undefined

	// You cannot reconfigure existing properties.
	try {
		Object.defineProperty(myObj, "name", {
			get() {
				return "Susan";
			},
		});
		console.log(myObj.name);
	} catch (e) {
		console.log(e); // TypeError: Cannot redefine property: name
	}

	// You cannot change property values.
	myObj.name = "Susan";
	console.log(myObj.name); // Ali
	try {
		Object.defineProperty(myObj, "name", {
			value: "Aria",
		});
		console.log(myObj.name); // Ali
	} catch(e) {
		console.log(e); // TypeError: Cannot redefine property: name
	}

	// You can add new properties to the prototype.
	myObj.__proto__.age = 14;
	console.log(myObj.age); // 14

	// You cannot change the prototype.
	try {
		Object.setPrototypeOf(myObj, {
			grade: 9,
		});
		console.log(myObj.grade);
	} catch (e) {
		console.log(e); // TypeError: #<Object> is not extensible
	}
	try {
		myObj.__proto__ = {
			grade: 9,
		};
		console.log(myObj.grade);
	} catch (e) {
		console.log(e); // TypeError: #<Object> is not extensible
	}

In short, Object.freeze prevents extensions to the object and makes all the existing properties non-configurable, and also prevents the values of the existing properties from being changed. In this way, the object becomes immutable.


Related Posts

comments