Sharing Variables Between Files (Without Globals)

machineghost

It was my understanding that variables created with let in Javascript cannot be global. I thought that meant that the variable only lived in that particular file.

However, when I make a simple/contrived example:

A.js:

let a = 5;

B.js:

console.log(a);

index.html:

<script type="text/javascript" src="A.js"></script>
<script type="text/javascript" src="B.js"></script>

it logs 5! Strangely though if I log window.a, that logs as undefined, so a global variable is not being created.

My question is, how is the variable getting shared between files without being a global variable?

Icepickle

It stays inside the current scope, the most outer block scope (or global scope as Bergi so nicely mentions), so this would work

<script>
let world = 'world';
</script>
<script>
console.log( `hello ${world}` );
</script>

Where as this would not

<script>
{
  let world = 'world';
}
</script>
<script>
console.log( `hello ${world}` );
</script>

it really doesn't matter that you are using 2 different files. In the end, all the scripts that get loaded get put behind each other, optimized and executed

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related