Chris Chris - 4 months ago 7x
Javascript Question

Why can external JavaScript files access other external JavaScript files functions and how to stop it?

I am by no means a guru with JavaScript, so my apologies if this questions sounds "beginner". But why is it that if I have 3 JavaScript files in a project, that any of those 3 JavaScript files can call any of the other functions that are in the other JavaScript files?

The bigger question is how can this be stopped? an example would be if, of these 3 hypothetical JavaScript files, just say they are named as ManagerJS.js, TeamAJS.js and TeamBJS.js, I don't want TeamAJS to be able to access TeamBJS but I want them both to be able to access ManagerJS.


All scripts on a page are evaluated in global scope. There is a single shared global scope per page.

You can prevent access by not defining stuff in global scope. You can use an IIFE to create a private scope for each script:

// myScript.js
(function() {

  // everything declared here is *local* to this function
  var localValue = 42;

  // we could expose values by explicitly creating global variables
  // (but there are other, more elaborate ways)
  window.globalValue = 21;


Only expose values that you want other code / scripts to access. There are various ways to do that, one of them is the revealing module pattern.

See also What is the purpose of a self executing function in javascript?