Reflect in JavaScript
Many of the functions for general operations are distributed across a bunch of objects and keywords in JavaScript. This increases the cognitive load and increases the number of times a language operation needs to be looked up. Here are a few quick examples:
const obj = { property1: 'value1', property2: 'value2', }; delete obj.property1; Object.preventExtensions(obj); try { obj.property3 = 'value3' } catch(e) { console.log(e.message); } console.log(obj); // { property2: 'value2' }
Reflect simplifies this by providing a consistent API for all of the operations:
const obj2 = { property1: 'value1', property2: 'value2', }; Reflect.deleteProperty(obj2, 'property1'); Reflect.preventExtensions(obj2); const succeeded = Reflect.set(obj2, 'property3', 'value3'); if (succeeded !== true) { console.log('Failed to set "property3", obj is not extensible'); } console.log(obj2); // { property2: 'value2' }
Notice how Reflect.set does not return an error and returns if the value was set instead. Even for basic operations, reflect can help clarify the code more
Those were just a few examples, you can view the full list here. Since Reflect provides a consistent API for many operations, it should generally be used instead of all the separate interfaces when it is available. There are exceptions when the syntax is more clear though; except for cases like the above, setting variables with obj.a = 'value' is usually clearer than Reflect.set(obj, 'a', 'value'). It is supported in all browsers including MS Edge, but not IE 11.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/reflect.js














