Add a property

Well I can for example use Object.defineProperty() like this,

Object.defineProperty(myObj, "lastName", { value: "Travolta" });

But how exactly do I know that lastName property has been created?

This case I have to use a try/catch to see if that lastName property is defined.

try {

Object.defineProperty(myObj, "lastName", { value: "Travolta" });

// Yeah is defined

} catch {

// error

}

the simplest option in that case is,

Add a property with Reflect

In this particular case we are going to add a property with Reflect.defineProperty(), which returns a Boolean so it is easier to check if our object property exists.

So let´s apply Reflect.defineProperty() to our example.

if ( Reflect.defineProperty(myObj, "lastName",

{ value: "Travolta", configurable: true, writable: true}) ){

// Yeah is defined

console.log(myObj.lastName) // Travolta

} else {

// Not defined

}

Super simple no?