5

Using eslint with React configurations I get an error when using Object.defineProperty. The error says:

Avoid using Object.defineProperty, instead use Reflect.defineProperty. (prefer-reflect)

On the eslint documentation of prefer-reflect they say it's deprecated, the reason being:

The original intent of this rule now seems misguided as we have come to understand that Reflect methods are not actually intended to replace the Object counterparts the rule suggests, but rather exist as low-level primitives to be used with proxies in order to replicate the default behavior of various previously existing functionality.

Then my question is: is there any advantage in using Reflect.defineProperty instead of Object.defineProperty?

Daniel Reina
  • 5,764
  • 1
  • 37
  • 50

2 Answers2

5

There is a slight difference between Object.defineProperty and Reflect.defineProperty: the former returns the target object and throws an exception when the descriptor could not be applied (e.g. when the property is non-writable or non-configurable or when the object is non-extensible), while the latter does return a boolean value whether it worked.

I'd argue that this makes Object.defineProperty a bit more useful, unless you're implementing a defineProperty proxy trap.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

Just to complement the last answer, with Object.defineProperty you must use a try/catch block for contolling exceptions while with Reflect.defineProperty you just can do a boolean check with an if statement for correct property creation.

Yago Lopez
  • 79
  • 2
  • 8