0

I recently came across this http://www.w3schools.com/js/js_scope.asp where I learned about "Automatic Global variables". Here is how you use it:

// code here can use carName

function myFunction() {
    carName = "Volvo";

        // code here can use carName
}

However, how high can it go? I am worried other files can access it to if its that global. If I am using AngularJS, can other controllers use it? Can other files use it?

John
  • 123
  • 1
  • 8
  • What do you mean other files??? FYI: w3schools is not the best reference out there. – epascarello Aug 21 '15 at 16:46
  • other modules. (which have their own controllers) – John Aug 21 '15 at 16:47
  • Global is global, anything can use them. There is no relationship between a JS file and scope, it is like they are all in one big file. That is why using `var` is important and not polluting the global namespace is important. – epascarello Aug 21 '15 at 16:47
  • http://stackoverflow.com/questions/1470488/what-is-the-function-of-the-var-keyword-and-when-to-use-it-or-omit-it – epascarello Aug 21 '15 at 16:56

1 Answers1

0

In JavaScript, creating a variable without var is the same as setting it on the global object as a property (and in the browser, global is window:

nameWithoutVar = 1;
// the above is the same as
window.nameWithoutVar = 1;

This means that any other script loaded in the browser for the page can access nameWithoutVar, the same as they can access location, document, etc.

Global variables are considered an extremely bad idea for this reason, because everything is using the same namespace. If you must use a global variable, be sure to document it, and try to namespace it so that it is unlikely to conflict with any other variable.

If you're not sure, you probably don't have to.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293