Objects are everywhere in JavaScript. Getting more knowledge of objects will definitely help you at some point in your journey. In this post, we will discover some properties and methods of objects that most the developers don't know about or didn't find useful.
I hope you are already familiar with the syntax of creating an object.
let obj = { key: "value" }
But did you know we can make lots of customizations on these keys and values?
Object.defineProperty
method gives you the power to control the behavior of a property. Let's see how it works.
let obj = {}
Object.defineProperty( obj, "a", {
value: 1,
writable: false,
configurable: true,
enumerable: true
} )
defineProperty
takes three arguments.
- The object in which you are trying to create a property.
- Name of the property.
- A configuration object.
Now let's talk about configuration object.
value
Value could be any valid value you want to set on the key (a).
Writable
If you set writable as false. You will not be able to edit the value.
obj.a = "new value" // Oops, not allowed.
Configurable
If we set configurable
as true. We can change the behavior at any time with the same defineProperty
method, but if you set it to false
, you will not able to change it again. It's a one-way operation.
Enumerable
If we set enumerable to false, it will not be shown in enumerations like for...in
loop.
Now, let's take a look at some builtin methods that prevent the extension of an object.
preventExtensions
As its name suggests. It will prevent you from setting more properties on an object.
let obj = { a: 1 };
Object.preventExtensions( obj );
obj.b = 2; // in strict mode it will throw an error.
console.log( obj.b ) // undefined
Seal
This method works the same as preventExtensions
, but it makes all existing properties as configurable: false
. So you can't add new properties and also can't reconfigure it. Again one-way operation.
let obj = { a: 1 };
Object.seal( obj );
obj.b = 2; // in strict mode it will throw an error.
console.log( obj.b ) // undefined
Freeze
This is the highest level of immutability. Freeze set all "data accessor" of an object as writable: false
.
let obj = { a: 1 };
Object.freeze( obj );
obj.b = 2; // in strict mode it will throw an error.
console.log( obj.b ) // undefined
These are the methods I found useful and interesting. If you know some more interesting methods, please comment down below. I will back with another exciting post, until then Bye.
Top comments (0)