How to find out the caller function in JavaScript?

Sometimes, the developer may want to modify how a function works on the basis of its caller function. To find out the caller function name, we will use the Function object’s caller property.

Property used:

  • Function.caller

Here, the Function object is replaced by the name of the function of which we want to know the parent function name.



Let’s take a look at an example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script >
    // Child function 
    function Foo() {
    
      // This will print 'Bar' 
        console.log(Foo.caller.name); 
    }
     
    // Parent function 
    function Bar() {
    Foo();
}
  
Bar();
  
</script>

chevron_right


When the above code is executed, we can see the name of the parent function being logged out.
Output:
Running code in Firefox console

Let’s take a look at another example:
Suppose we call the Foo function from multiple functions.

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    // Child function 
    function Foo() {
    
        // This will print parent function's name
        console.log(Foo.caller.name);
    }
  
     // Parent function
     function Geeks() {
          Foo();
     }
  
     // Parent function 
     function Fun() {
          Foo();
     }
  
     // Parent function 
     function Sam() {
          Foo();
     }
  
Geeks();
Fun();
Sam(); 
</script>

chevron_right


Output:
Calling child from multiple functions

You can know more about the parent function from the property Function.caller



My Personal Notes arrow_drop_up

Full stack web developer | GCI 18 Mentor | JSec at IIITV Coding Club

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.