JavaScript | Reflect.apply() Method

The Reflect.apply() method is a standard build-in object in JavaScript which is used to call a function using the specified argument. It works similar to the Function.prototype.apply() method to call a function, but in a efficient manner and easy to understand.

Syntax:

Reflect.apply(target, thisArgument, argumentsList)

Parameter: This method accepts three parameters as mentioned above and described below:

  • target: This parameter is the target function which is going to be called.
  • thisArgument: This parameter has the this value which is required for the calling the target function.
  • ArgumentsList: This parameter is an array-like object specifying the argument with which target should be called.

Return Value: Calling the given Target function resulted in the specified this value and arguments.

Exceptions: A TypeError is exception given as the result, when the target is not callable.



Below examples illustrate the Reflect.apply() Method in JavaScript:

Example 1: List argument is passed and dictionary – object is created.

filter_none

edit
close

play_arrow

link
brightness_4
code

function geeks1 (a, b, c) {  
    this.x = a;  
    this.y = b;  
    this.z = c;  
}const obj = {};  
Reflect.apply ( geeks1 , obj, [12,42,32] );  
console.log( obj );  

chevron_right


Output:

{ x: 12, y: 42, z: 32 }

Example 2: In this example, the empty list argument is passed and the function is called. And the second portion contains mathematical computation, finding the minimum element from the list.

filter_none

edit
close

play_arrow

link
brightness_4
code

var geeks2 = function() { console.log(this); }  
Reflect.apply(geeks2, 'GeeksforGeeks', []);  
    
var list= [31, 45, 143, 5];  
console.log(Reflect.apply(Math.min, undefined, list)); 

chevron_right


Output:

String { "GeeksforGeeks" }
5

Example 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Converting the list of integer into char string
console.log(Reflect.apply(String.fromCharCode, 
    undefined, [103, 101, 101, 107, 115, 102, 
          111, 114, 103, 101, 101, 107, 115]))
   
// Extract the indexed value of string(character)
console.log(Reflect.apply(''.charAt, 'shubham', [3]))

chevron_right


Output:

geeksforgeeks
b

Supported Browsers: The browsers supported by JavaScript Reflect.apply() Method are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari
  • Edge

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai