How can I retrieve the value of a constant using a string as its name, where the constant is an arrow function?
const foo = (bar) => { return bar }
I tried accessing it through the window object but got undefined:
let fn = window['foo'] // undefined
Currently, the only solution I found is to use the older function syntax:
function foo(bar) { return bar }
let fn = window['foo'] // function foo(bar) { return bar }
Is there a way to get the function from a string when it's stored as a constant?
Edit:
To clarify why I prefer defining functions this way, consider scope and mutability. Arrow functions' handling of the this
keyword is more predictable and constants provide some level of safety against unintentional changes.
The potential for mutable variables in JavaScript can lead to unexpected behavior. For example:
function foo(bar) { return bar }
// Somewhere else in your code
let foo = 4;
// Later on
foo("return this string please") // foo is not a function.
In conclusion, defining functions as arrow functions within constants reduces mutability and minimizes surprises related to this
.