Reflect
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect
The Reflect
namespace object contains static methods for invoking interceptable JavaScript object internal methods. The interceptable means it is possible to stop, validate, redefine respective method before it returning the result. The methods used are same as the proxy handlers
.
Reflect
can't be initiated with new
operator, or all methods in Reflect
are static just like Math
. It will provide list of static functions with the same names that proxy handler supports.
Key Characteristics of Reflect
- Static Methods Only:-- Reflect is not a constructor, so creation of instance with
new
operator not possible. It is purely collection of static methods likeMath
. - Functional Alternative:-- Provides functional equivalents to operators or methods like
in
,delete
and properly manipulate. - Improved consistency:-- When performing operations on objects, would return
true
orfalse
instead of throwing error. It will allow to write cleaner code. - Customize proxy handlers:-- The
Reflect
methods combined with proxy handlers would allow to write custom behavior.
Example
Below example demonstrate how using Reflect would make difference in execution and writing code.
// With traditional syntax
const obj1 = Object.freeze({ foo: 10 });
obj1.bar = 20;
When this peace of code executed from chrome consul it would not throw error, because chrome by default uses non-strict mode and as per ECMA specification the code silently fails instead of throw error. But when strict mode enforced the code would throw error that we were expecting. take a look into below two images
Result in chrome with non strict mode
Result in chrome with strict mode
Result in node.js
When you trigger this peace of code in node.js which is by default uses strict mode it would always fail
Now lets try same with Reflect
, as explained already the result is predictable and Reflect methods would always returns either true / false instead of throwing errors.
Lets try to execute below peace of code in node.js
// With Reflect
const obj2 = Object.freeze({ foo: 10 });
const result = Reflect.set(obj2, "bar", 20);
console.log(result); // false
console.log(obj2); // { foo: 10 }
Result in nodejs for Reflect
Additionally when writing same peace of code in typescript you can notice compilation error before hand.