0

If JavaScript has function level scope, is wrapping all my JS code inside

$(document).ready(function() { ... }); 

enough to prevent global namespace pollution? If not, is there a better way I can do it?

Aswin Koliyot
  • 588
  • 1
  • 7
  • 11
  • You should be looking for why you're polluting the global namespace within your code rather than wrapping your code inside here. – Oliver Hemsted May 15 '17 at 10:21

2 Answers2

3

It's a good start, but you also need to ensure you don't create any global variables in the function. Setting strict mode (with "use strict";) should go most of the way for doing that. Checking every mention of window will go the rest of the way.

It does have the side effect of delaying execution of the code until the DOM is ready. That isn't always desirable. You might want to use a simple IIFE instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Yes, this is mostly enough.

Because JavaScript has function scope to hide members, new members declared within it are hidden from the global scope.

You need to ensure to declare them though (i.e. var variableName) inside the function, or they will be hoisted to the enclosing scope (which may be global).

If course, assigning variables directly to the global object will pollute it (just mentioning this for completeness).

As Quentin answered, using strict mode with use strict; will ensure you do not have undeclared variables that would otherwise attach to the global context.

Community
  • 1
  • 1
DigiFriend
  • 1,164
  • 5
  • 10