DEV Community

Yuta Kusuno
Yuta Kusuno

Posted on • Updated on

[JS] The top-level scope is NOT always the global scope

Understanding the scope in JavaScript is crucial for writing robust and maintainable code. While in browsers, the top-level scope has historically been synonymous with the global scope. And it is also called the global object shared by all scripts. However, Node.js has a noteworthy distinction. The top-level scope is not the global scope. I will delve into the difference between the top-level scope in browsers and Node.js using globalThis, which can access to the global object in the both JavaScript environments.

The Global Scope in Browsers

In traditional browser environments, any code that does not specifically start up as a background task has a Window as its global object. When a variable is declared using var outside of any function or block, it becomes a global variable associated with the Window object. Let us illustrate this with a simple example:

// Browser Example

<script>
  var globalVar = "I am global";

  console.log(globalVar); // Outputs: I am global
  console.log(globalThis.globalVar); // Outputs: I am global
</script>
Enter fullscreen mode Exit fullscreen mode

In this case, globalThis is the Window object. globalVar is accessible globally and can be accessed from the top-level scope associated with the Window object.

However, if I add the type="module" to the script tag, the result changes.

// Browser Example

<script type="module">
  var localVar = "I am local";

  console.log(localVar); // Outputs: I am local
  console.log(globalThis.localVar); // Outputs: undefined
</script>
Enter fullscreen mode Exit fullscreen mode

ECMAScript evaluates the internal code as a Module rather than a Script. The top-level var creates a global variable in Script, while it does not in Module scope.

A Different Point in Node.js

On the other hands, Node.js has different behavior from browsers. Scripts running under Node.js have an object called global as their global object. Variables declared with var at the top level of a module are local to that module. Let us demonstrate this with an example.

// Node.js Example

var localVar = "I am local";

console.log(localVar); // Outputs: I am local
console.log(globalThis.localVar); // Outputs: undefined
Enter fullscreen mode Exit fullscreen mode

In this case, localVar is scoped to the module, and attempting to access it from another module would result in an undefined variable.

In both Node.js CommonJS modules and native ECMAScript modules, top-level variable declarations are scoped to the module, and do not become properties of the global object.

That is about it. Happy coding!

Top comments (1)

Collapse
 
sona21 profile image
Sona1

Thanks for sharing ☺️