1

I have two javascript files with variables with same name, how can I define which one to use ?

Liam
  • 27,717
  • 28
  • 128
  • 190
user5783530
  • 221
  • 1
  • 4
  • 16
  • You need to use a [closure](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work). – Liam Sep 08 '16 at 10:41
  • 2
    javascript variables are shared between files, this means if you use the same variable name in both files, it will be the same variable. To solve this you can either use a prefix or as Liam suggested use closure – Terry Sep 08 '16 at 10:42
  • 1
    Maybe you can try some [Namespacing](http://stackoverflow.com/questions/881515/how-do-i-declare-a-namespace-in-javascript)?! – mhyassin Sep 08 '16 at 10:43
  • 1
    you need to understand scopes like @rellyethan suggested –  Sep 08 '16 at 10:44

2 Answers2

5

In Javascript, you can't actually have 2 variables made with different goals and have the same name in the same scope.

Basically, there're 2 types of scope: global and local. Global scope is what you're facing making 2 variables with the same name in different files.

Once, that was a common issue and developers agreed to try making files with different scopes and use global scope only when it's necessary and inevitable.

So, the most common way to create a new scope (local) is to close your code in function. Functions in javascript create a new scope, which is inaccessible from the global, but you still can reach the global scope from the local one.

Also, there're 2 ways to keep your code modular (1 file = 1 module): either using AMD or CommonJS modules.

More about scopeshere.

1

Imagine the following scenario:

<html>...

<script src="file1.js">var x = "pizza";</script> 
<script src="file2.js">var x = "cheese";</script>
<script src="file3.js">var x = "chocolate";</script>

Your shared variable will always be overwritten by the latest value it has been given, in this case "chocolate".

If you want to split them up, either use a prefix or consider changing the names since once they are loaded into the main file, they are in the same namespace.

console.log(x); // chocolate will be printed since it is the last value it was (re)defined as.
</html>

EDIT:

If you want it to work, the simplest way would be to change the variables' names.

<script src="file1.js">var x = "pizza";</script> 
<script src="file2.js">var y = "cheese";</script>
<script src="file3.js">var z = "chocolate";</script>

console.log(x); //pizza
console.log(y); //cheese
console.log(z); //chocolate
Tom Nijs
  • 3,835
  • 3
  • 22
  • 40
  • 2
    I'm not sure how this helps? this appears to be an illustration of the problem, not a solution – Liam Sep 08 '16 at 10:49
  • I mentioned how he can solve the problem, I doubt there's a need to show how to change a variable's name. Added the solution, none the less. :) – Tom Nijs Sep 08 '16 at 10:49