What is the purpose of the script area?

When checking function areas in the DevTools console, I noticed a "script" area. After a little research, it is created for the let and const variables.

Areas of function in script variables without const or let :

global scope

Function areas in a script with let variable:

global scope and scope <w371

However, the following paths 1 in the console: variables in the script area can be accessed from other scripts:

 <script>let v = 1</script> <script>console.log(v)</script> 

I heard about ES6 modules in which top-level variables will not be accessible from outside the module. Is this what scope is used or has a different purpose?

+5
source share
1 answer

When you declare a variable with var at the top level (i.e. not inside the function), it automatically becomes a global variable (therefore, in the browser you can access it as a window property). It is different from variables declared with let and const - they do not become global variables. You can access them in another script tag, but you cannot access them as window properties.

See this example:

 <script> var test1 = 42; let test2 = 43; </script> <script> console.log(test1); // 42 console.log(window.test1); // 42 console.log(test2); // 43 console.log(window.test2); // undefined </script> 
+6
source

Source: https://habr.com/ru/post/1259990/


All Articles