0

Suppose I have a JavaScript function like this:

function f(DOM_Path) {
  if (typeof DOM_Path !== 'undefined') {
    // Do something
  }
}

Now suppose I were to pass this a variable identified by its DOM path like so:

f(document.html);

This would throw an error if document.html were undefined even before f() checked for this. To get around this, I'd need some way to pass the path to the variable as a string, like so:

f('document.html');

But if I do this, how can I edit f() to check whether the variable at this path is undefined, and otherwise use the path as the path to a variable rather than a string?

tog22
  • 486
  • 1
  • 4
  • 21
  • Are you looking for something like this: `f(document.html || 'document.html');` – Get Off My Lawn Mar 12 '19 at 16:20
  • Why would throwing an error outside of `f()` be undesirable? Can you please explain your use case with a little more detail? – Ryan Mar 12 '19 at 16:21
  • You said"_This would throw an error if document.html were undefined even before f() checked for this _" but `f(document.html);` will not throw any error – Maheer Ali Mar 12 '19 at 16:22
  • 3
    It's virtually impossible to do this sanely, especially with *arbitrary, non-global variables*. But something like `f(document, 'foo.bar')` is perfectly possible. You need to ensure at least the "starting variable" exists. – deceze Mar 12 '19 at 16:26
  • This feels like an X/Y problem. What are you really trying to achieve with this. – Ian McLaird Mar 12 '19 at 16:30
  • @deceze's example of `f(document, 'foo.bar')` is demonstrated in the duplicate question: https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key – tog22 Mar 13 '19 at 19:20

0 Answers0