yarek
yarek

Reputation: 12064

How to call anonymous functions in chrome developer tool?

Here is my code:

(function(params) {
  function sayHi(text) {
    console.log(text);
  }
  sayHi("Hello world")
})()

How can I call the sayHi() function from chrome developer tools ?

Upvotes: 0

Views: 1200

Answers (1)

Quentin
Quentin

Reputation: 944320

sayHi is scoped to the IIFE it is declared inside.

You can therefore only call it:

  • From the same scope
  • From a scope you copy the function to

From the same scope

You need to move the scope of the Chrome Console into the function. You can do this by adding a breakpoint inside the IIFE (via the Sources panel) and then causing the IIFE to rerun by reloading the page.

Then you can call the function as normal.

Animation showing how to add a breakpoint

Copy the function to a different scope

This requires that you edit the source code. The general way to do this is by returning a value from the IIFE.

const sayHi = (function(params) {
  function sayHi(text) {
    console.log(text);
  }
  sayHi("Hello world");
  return sayHi;
})()

sayHi("This can now be called from outside the function, if this is the global scope it will be accessible to the Chrome Console");

Upvotes: 2

Related Questions