user1015711
user1015711

Reputation: 132

Multiple script tags variable conflict?

I have multiple script tags in a web page. Will having the same variable name in more than one script tag cause issues with the variables getting the wrong value from an above script tag?

<script type="text/javascript">
   var current = 0;
</script>

<script type="text/javascript">
   var current = 1;
</script>

Will the first current cause issues with the second occurence?

Upvotes: 1

Views: 1425

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

You won't ever run into a situation where code that's executed immediately after the var current = 1 in your second <script> tag will be using current with a value other than 1. To provide a very basic example:

<script type="text/javascript">
   var current = 0;
   alert(current); // will always alert 0
</script>

<script type="text/javascript">
   var current = 1;
   alert(current); // will always alert 1, never 0
</script>

That should answer the "cause issues with the variables getting the wrong value from an above script tag" aspect of the question.

Upvotes: 0

jAndy
jAndy

Reputation: 236022

Yes it will. There is only one global execution context, doesn't matter how many <script> nodes you have in your HTML markup.

So in this particular example, current gets initialzed on the window object with 0 and then gets overwritten with 1.

Upvotes: 4

Related Questions