2

I'm getting hung up on why Javascript globals are so dangerous, when a similar (?) behavior is in Ruby. When you make a variable, like foo, and it's bound to main, isn't that the same thing as having a Javascript variable bound to window?

Casey Chow
  • 1,794
  • 4
  • 17
  • 29
  • 2
    Global variables are a bad idea in *any* language. – Pointy Aug 07 '11 at 21:38
  • I got that much. But why is it, in Ruby, that it seems that variables bound to the default object aren't considered bad when in Javascript the same thing is? – Casey Chow Aug 07 '11 at 21:45
  • Not a bad idea by itself, but an idea that can (and is) way too often misused and abused. – Mchl Aug 07 '11 at 21:46

2 Answers2

1

Actually, top-level locals in Ruby are not very much like global variables, because they cannot be accessed (using normal lexically-scoped references) from within methods or classes or modules.

And global variables are only a problem in systems that are large enough to have an object hierarchy or multiple modules. If you only use one scope, it doesn't make any difference if it's global or not.

So in a Ruby script, in a single file, that might do something like update your name server's zone file, you (a) can't access those top level locals except at the top level, and (b) it's OK to use global variables in a tiny little program written at the global level.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • More explicitly: When you write `x = foo` in JavaScript without declaring `x` first, it's equivalent to `window.x = foo` — every statement like that is working with the same global variable. But the equivalent to `window.x = foo` in Ruby is not `x = foo`, it's `$x = foo` — you have to go out of your way to make a global variable in Ruby. A top-level local is not globally visible. – Chuck Aug 07 '11 at 22:11
0

In a simple program (of any language) where:

  1. A single developer knows all the code.
  2. That single developer is the only one who works on the code.
  3. There are no third party libraries being used that might also have globals.
  4. There is no asynchronous, timer-based or threaded code using globals.

Then, globals might be trouble-free.

The challenge (in any language) is that you will rarely find that all these are true and the consequences for messing up can be bad with tricky, hard to find, hard to reproduce bugs. And, even projects that start out this way can morph into projects that are no longer this way and then you've got a tricky code base that's hard to work on.

So ... globals should generally be avoided whenever possible. Local variables or object-based variables are so much easier to stay safe with.

jfriend00
  • 683,504
  • 96
  • 985
  • 979