What is variable declared within file scope in javascript?
Is there anything file scope, considering multiple files are used in an app.
Asked
Active
Viewed 7,659 times
7

c g
- 389
- 1
- 4
- 11
-
1Do you mean global scope? Module scope? I've never heard of 'file scope'. – Andrew Li Jul 05 '17 at 02:30
-
2It depends on whether you use modules. – SLaks Jul 05 '17 at 02:30
-
1There 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 Answers
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 export
ed).

SLaks
- 868,454
- 176
- 1,908
- 1,964
2
In JavaScript, there are only 3 types of scope:
- Global Scope (i.e. every variable/function defined outside functions in a file or multiple files)
- Functional Scope (i.e. every variable/function defined within the function)
- Closure Scope (i.e. code block/function having access to its surrounding lexical scope)

Navneet Goel
- 134
- 4
-
7Since 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
-
5Also Javascript now has block-level scope, when you use `const` or `let`. – machineghost Sep 18 '18 at 20:24