javascriptanonymous-functionweb-console

How to work with javascript functions in an anonymous function in the browser console?


I've found an interesting method of defining functions:

! function() {
  function myFunction() {
    return returnValue;
  }
}();

However, this function can not be called directly from the browser console, how could I achieve it?


Solution

  • That is an IIFE (immediately invoked function expression) wrapped around your function.

    I would suggest using this approach for the code that you've written:

    !function() {
      function myFunction() {
        return 'hello';
      }
    
      window['myFunction'] = myFunction;
    }();
    

    Now call myFunction in the console. Previously myFunction was hidden inside your IIFE and was not exposed as a global.