machineghost
machineghost

Reputation: 35790

Sharing Variables Between Files (Without Globals)

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?

Upvotes: 2

Views: 173

Answers (2)

Icepickle
Icepickle

Reputation: 12796

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

Upvotes: 3

Webber
Webber

Reputation: 5494

It's a regular variable in the global scope.

Using multiple script sources doesn't mean using multiple interpreters.

Upvotes: 1

Related Questions