1

What happens if I declare two variables with the same name and scope?

var foo = (function() {
    return {
        alertMe: function() {
            alert("foo1");
        }
    }
})();

var foo = (function() {
    return {
        alertMe: function() {
            alert("foo2");
        }
    }
})();

foo.alertMe();

I'm asking because I'm dynamically loading little portlets on my website and each portlet has its own script tag with a JavaScript module. The problem is, users can duplicate portlets which means there is a good chance something like the above may happen.

Silician75
  • 21
  • 1
  • 4

3 Answers3

6

In your example they're both undefined anyway, so you'll have a value of undefined.

Anyway, the second var is ignored. You'll have the same result as though you didn't have it, meaning foo will be overwritten with the new value.

So, same result as if you did:

var foo = (function() {
    alert("foo1");
})();

foo = (function() {  // I'm overwriting the value of "foo"
    alert("foo2");
})();

EDIT: The code in the question changed. The result is now more observable if you run the code. The foo variable's reference to the first object is replaced with a reference to the second. The first reference is lost.

user113716
  • 318,772
  • 63
  • 451
  • 440
0

last variable will work, in your example, first var will be ignored `var foo = (function() { alert("foo1"); })();

foo = (function() { // I'm overwriting the value of "foo" alert("foo2"); })(); `

D.Shinekhuu
  • 307
  • 3
  • 12
0

To avoid this problem encapsulate java scripts of different modules in different name spaces.

Name space explanation

You can also look at

How do I declare a namespace in JavaScript?

Community
  • 1
  • 1
dhinesh
  • 4,676
  • 2
  • 26
  • 44