0

I want to be able to define a function (either regular or arrow) globally in the js window like this:

function myRegularFunction(){
   console.log("hello from the regular function");
}
const myArrowFunction = () => {
   console.log("hello from the arrow function");
}

and then be able to invoke it elsewhere like this:

window['myRegularFunction']();
window['myArrowFunction']();

When I define functions as stated above, I am then able to inovke the regular function, but the arrow funcion is not appearing in the js window, and thus I cannot invoke it. From the console, I get: window['myArrowFunction'] undefined

Can anyone help me with this issue?

B2391
  • 1
  • 1
  • You could just call `myArrowFunction()`. Putting simply, when you do arrow function it won't be registered as window "property" but it will be available globally – Nikita Chayka Nov 23 '22 at 17:35
  • 1
    A top-level function declaration gets assigned to the window. Variables declared with `const` or `let` (including arrow functions) do not. – CertainPerformance Nov 23 '22 at 17:35
  • This shouldn't have been closed based on the cited references; the "problem" (feature not bug) is `const` and `let` are block (/module) scoped. Old JS implicitly put global function declarations (functions declared outside of other functions) on the `window` object. It *also* did the same for variables. `var x = 0; window.x; // 0`. It has nothing to do with it being an arrow function, or a function at all. If you want to export a const, you need to `export` it, or put it on an object that is. `const arrow = () => {}; window.arrow = arrow;` New JS makes you be explicit; that's a good thing. – Norguard Nov 23 '22 at 18:02

0 Answers0