1
votes

With eslint you can declare a global variable with /* global <name-of-var> */. For example

/* global document */

const elem = document.querySelector(selector);

Is it possible to declare a global but only inside a certain scope?

function foo(selector) {
  /* global document */
  return document.querySelector(selector);
}

function bar(selector) {
  return document.querySelector(selector);  // error! document undefined
}

Testing the example above fails in that declaring document as a global in foo makes it accesseble in bar.

The advantage making the global's access scoped is that if you delete a function there is nothing else to clean up. It declares it's own access. Where as if you put the globals at the top of the file and delete a function you also have to go clean up the top of the file. It also arguably better documenting where the variable comes from based on the idea that more info locally is better.

Note: while I know the feature is different, python has the concept of giving an individual function access to a global. Doing so does not give all functions access to that global so the idea in general of declaring globals per function is not unusual.

Is there a way declare the existence of global only within a certain scope for eslint?

1
You might want to use the browser option instead of explicitly mentioning globals that are provided by browsers. - Quentin
Thanks but no, I absolutely do NOT want to use the browser option. With the browser option eslint can't figure out undefined variables because it has to assume they exist on the browser object. See this - gman

1 Answers

0
votes

The documentation doesn't say anything about doing it only locally in a function. I can see the point of what you're describing; you never know, they might be open to a pull request adding that...

Two workarounds for you:

  1. Group together the functions that need the global in their own module.

  2. Use eslint-disable-line or eslint-disable-next-line and an inline assignment, like this:

    function foo(selector) {
      const doc = document; /* eslint-disable-line no-undef */
      return doc.querySelector(selector);
    }