7

What is variable declared within file scope in javascript?
Is there anything file scope, considering multiple files are used in an app.

c g
  • 389
  • 1
  • 4
  • 11
  • 1
    Do you mean global scope? Module scope? I've never heard of 'file scope'. – Andrew Li Jul 05 '17 at 02:30
  • 2
    It depends on whether you use modules. – SLaks Jul 05 '17 at 02:30
  • 1
    There is no "file scope". There is global, function, eval or (recently) block. – RobG Jul 05 '17 at 02:32
  • @SLaks, we are using es6 import statements in the app. Can there be any thing linked to it? If I can get any link to read on to clear this confusion that will be very helpful. – c g Jul 05 '17 at 03:36
  • @AndrewLi I didnt know about module scope, I will read on it. thanks! – c g Jul 05 '17 at 03:38
  • Apparently, there is no "official" concept of _file scope_ - nor of _module scope_, but I like the idea that such a home made concept conveys (the same variable name used in _two different and completely unrelated_ global scopes - presumably in two different files having no exports or imports obviously have different scopes). Two good references: https://blog.bitsrc.io/understanding-scope-and-scope-chain-in-javascript-f6637978cf53 and https://2ality.com/2015/02/es6-scoping.html. – Henke Jan 28 '21 at 10:49

2 Answers2

15

ES6 modules form their own file scope (as if the entire contents of the file were wrapped in a function).

Variables declared in a module are completely inaccessible from outside that module (unless they're exported).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

In JavaScript, there are only 3 types of scope:

  1. Global Scope (i.e. every variable/function defined outside functions in a file or multiple files)
  2. Functional Scope (i.e. every variable/function defined within the function)
  3. Closure Scope (i.e. code block/function having access to its surrounding lexical scope)
Navneet Goel
  • 134
  • 4
  • 7
    Since your "Closure scope" is a combination of function and block, and you have function as #2, #3 should be "block". Closures are formed by scopes having access to outer scopes, so are an artefact of an ECMAScript [*Lexical Environments*](https://tc39.github.io/ecma262/#sec-lexical-environments) rather than a "scope" of their own. ;-) – RobG Jul 05 '17 at 03:46
  • 5
    Also Javascript now has block-level scope, when you use `const` or `let`. – machineghost Sep 18 '18 at 20:24