JavaScript Reflect is a built-in object that gives access to other elements for interceptable operations. This object can be used to check whether an object has a particular property or to change or add new properties to an existing object. This object cannot be explicitly created using the new keyword and we cannot call it a function. Reflect has a set of static functions to perform operations.
Syntax:
Reflect.staticFunc()
Parameters: This object does not have fix parameters, it depends upon the static function being used with it
Return Type: The return values depend on the function being used.
Example 1: This example uses Reflect method to check and add properties in a particular object.
Javascript
var details = { Â Â Â Â name: "Raj" , Â Â Â Â course: "DSA" , Â Â Â Â website: "geeksforgeeks.org" , } Â Â console.log(Reflect.has(details, "course" )) Â Â Reflect.set(details, "Rating" , "5" ); Â Â console.log(details) |
Output:
true {name: 'Raj', course: 'DSA', website: 'geeksforgeeks.org', Rating: '5'}
Example 2: This example uses Reflect functions to construct a new object.
Javascript
class Details { Â Â Â Â constructor(name, course) { Â Â Â Â Â Â Â Â this .name = name; Â Â Â Â Â Â Â Â this .course = course; Â Â Â Â } Â Â Â Â get fullDetails() { Â Â Â Â Â Â Â Â return `${ this .name} ${ this .course}`; Â Â Â Â } } Â Â var person = [ "Shobhit" , "DSA" ] Â Â var enroll = Reflect.construct( Â Â Â Â Details, Â Â Â Â person ); Â Â console.log(enroll instanceof Details); console.log(enroll); |
Output:
true Details {name: 'Shobhit', course: 'DSA'}
Example 3: This example uses Reflect methods to freeze an array so that new elements cannot be added to it.
Javascript
var arr = []; Â Â Reflect.set(arr, 0, "Hello" ); Reflect.set(arr, 1, "Welcome" ); Reflect.set(arr, 2, "to" ); Reflect.set(arr, 3, "neveropen" ); Â Â console.log(arr); console.log(Reflect.isExtensible(arr)) Â Â Reflect.preventExtensions(arr); Â Â Reflect.set(arr, 4, "DSA" ); Â Â console.log(arr) |
Output: Using the preventExtensions method new properties cannot be added to the array. This helps to freeze the array
(4)Â ['Hello', 'Welcome', 'to', 'neveropen'] true (4)Â ['Hello', 'Welcome', 'to', 'neveropen']
Supported Browsers:
- Chrome
- Edge
- Firefox
- Opera
- Safari
We have a complete list of JavaScript Reflect methods, to check please go through the JavaScript Reflect Reference article.