metarmask metarmask - 1 year ago 72
Javascript Question

What is the purpose of the script scope?

When inspecting scopes of a function in the DevTools console I noticed a "script" scope. After a bit of research it seems to be created for


Scopes of a function in a script without

the global scope

Scopes of a function in a script with a

a global scope and a script scope

Yet the following prints
in the console, the variables can still be accessed from other scripts:

<script>let v = 1</script>

I've heard of ES6 modules in which top-level variables won't be accessible from outside a module. Is that what the scope is used for or does it have any other purpose?

Answer Source

When you declare a variable using var on the top level (i.e. not inside a function), it automatically becomes a global variable (so in browser you can access it as a property of window). It's different with variables declared using let and const—they don't become global variables. You can access them in another script tag, but you can't access them as properties of window.

See this example:

  var test1 = 42;
  let test2 = 43;
  console.log(test1); // 42
  console.log(window.test1); // 42
  console.log(test2); // 43
  console.log(window.test2); // undefined

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download