0

I'd like to declare a global variable in an external javascript file and have it become accessible in the main window that loads the file.

So far the following methods have failed

var foo = 'bar';
window.foo = 'bar';

Only implicit globals seem to work

foo = 'bar';

However, people seem to recommend against ever using implicit globals. So what should I do in this case?

yosefrow
  • 2,128
  • 20
  • 29

2 Answers2

0

Both your solutions should work just fine, they define a variable in the global scope but you must make sure to include the JavaScript file that defines these variables before the scripts that are actually using them. Probably you forgot to include your all your script files or you just you have other errors in your code (check the browser's console for errors, F12 in Firefox).

That said it is a bad practice to use globals anyway. It makes your code hard to test, hard to debug and your globals can overlap with globals from third party javascript libraries (if you are using any of them).

Arpad Toth
  • 231
  • 2
  • 6
  • I'm using an IIFE to attach my code to a namespace so there is just one specially named global with all functions and variables attached to it. Is this still considered bad practice? – yosefrow Jul 05 '16 at 09:04
  • It depends, I would say that theoretically yes, It is still a bad practice but on the other hand, lots of popular frameworks use this approach and is OK. I done some code using this approach and I didn't have any issues but these days i feel that using a module loader such as browserify + commonjs is better. If you are using globals only for namespace names and you plan to use your code only on browser (no server side js) I think this is not necessarily a bad practice. It can actually simplify your design. – Arpad Toth Jul 05 '16 at 09:12
0

The issue was that I was attaching an IIFE to window and then calling it via window instead of directly.

window.foo = (function() {
    return {
        log: function() {
            console.log('bar function');
        }
    };
})();
window.foo.log();

Note: that this example actually works fine, but due to some content of my IIFE it did not work for me until I called it using just foo.log();

I'll look into this more later. As it interests me what part of my code caused this.

yosefrow
  • 2,128
  • 20
  • 29