defineProperty method in Javascript

defineProperty is a method on Object which allow you to configure the properties to meet some criterias.
Here is a simple example with an employee object with two properties firstName & lastName and append the two properties by overriding the toString method on the object.
You will get Output as : Jameel Moideen

I am going to change the same code by using defineProperty on the object

The first parameter is the name of the object and then second parameter is name of the property we are adding , in our case it’s toString and then the last parameter is json object which have a value going to be a function and three parameters writable,enumerable and configurable.Right now I just declared everything as true.

If u run the example you will get Output as : Jameel Moideen

Let’s understand why we need the three properties such as writable,enumerable and configurable.
writable
One of the very annoying part of the javascript is , if you change the toString property to something else for example

if run this again , everything gets breaks
Let’s change writable to false. If run the same again you will get the correct output as ‘Jameel Moideen’ . This property will prevent overwrite this property later.
enumerable
if you print all the keys inside the object , you can see all the properties including toString.
console.log(Object.keys(employee));
if you set enumerable to false , you can hide toString property from everybody else. If run this again you will get firstName,lastName
configurable

if someone later redefined the object on later for example enumerable to true and run it. You can see toString property came again.


we no need this behavior , so you can restrict this by set configurable to false.