0

I've learned that using globals is a bad idea in Javascript because there's the risk of collisions with dependencies.

Can I use var at the global scope as an alternative to this? I want to avoid the pitfalls of globals, but doing this seems much easier than passing along all my custom objects as parameters to functions. I have objects which are partially defined in many different files.

max pleaner
  • 26,189
  • 9
  • 66
  • 118
  • 3
    Using `var foo` in the global scope is the exact same thing for all intents and purposes. At the very least "namespace" it. – PeeHaa Jun 04 '16 at 19:42
  • I assume this is somehow related to your deleted question. See http://stackoverflow.com/q/37241112/218196 . – Felix Kling Jun 04 '16 at 19:44
  • Ways to avoid/reduce globals: [What is the (function() { } )() construct in JavaScript?](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) and [How do I declare a namespace in JavaScript?](https://stackoverflow.com/questions/881515/how-do-i-declare-a-namespace-in-javascript) – Jonathan Lonowski Jun 04 '16 at 19:44
  • Consider using [__`IIFE(Immediately-Invoked Function Expression)`__](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) – Rayon Jun 04 '16 at 19:45
  • @FelixKling It's a follow-up since the other one was being downvoted. It's not the same - I actually got an answer to the other question which is yes, `var` globally is the same as `global`. In this I was trying to find a way to avoid globals, though I suppose that's a duplicate as well ... – max pleaner Jun 04 '16 at 19:54
  • "*Can I use `var` at the global scope as an alternative to this? I want to avoid the pitfalls of globals*" sounds like you're contradicting yourself. – Bergi Jun 04 '16 at 20:03

1 Answers1

4

Can I use var at the global scope as an alternative to this?

var in global scope creates a global variable. So it's exactly the same and not in any way better.

If you are working with Node, there isn't really a need for globals. Every module should require all of its dependencies.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143