Search code examples
javascriptfunctionwindowconstantsarrow-functions

Where are JavaScript constants stored in browser?


I want to be able to take a string and use that to retrieve the value of a constant that has that string's name. In particular, the constant will equal an arrow function.

const foo = (bar) => { return bar }

I expected that it would show up in the window object, but it doesn't:

let fn = window['foo'] // undefined

Right now, the only way I can figure out how to do this 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 I can get the function from the string of its name, when the function is stored within a constant?

Edit:

I feel the need to clarify why I would want to start defining functions like this, as most responses have seemed to find the distinction important. It essentially comes down to scope and mutability.

The way arrow functions handle the this keyword is a little easier to grok with arrow functions and I believe should be the standard behavior unless the old behavior is explicitly required.

Second, the way mutability works with JavaScript, I think that defining functions as constants is a bit safer. Example:

function foo(bar) { return bar }
// Elsewhere
let foo = 4;
// Back at the ranch
foo("return this string please") // foo is not a function.

Ultimately, I think this just reduces mutability, and also causes fewer surprises when using this.


Solution

  • Only global variables get assigned a matching property on the global object. Nothing else, including constants, does.

    The value of a constant won't automatically appear anywhere except in the constant itself.

    If you want to access it via a string, then store it as a property of an object (preferably not the global object though, that's a disorganised mess with a significant risk of clashing with other code).