Does imported functions from the same source, have access to their source global variables?

Issue

OK i searched every site i knew, using every keyword i knew, but i found nothing close the subject i searched about, maybe the whole question is wrong, but anyway…

let’s say we have a module named Index.js, which contains a STORAGE and two functions responsible for reading/writing to STORAGE.

var STORAGE = []

function writeStorage(data) {
  STORAGE.push(data)
}

function readStorage(data) {
  //find data in STORAGE... and return result as RES
  return RES
}

Now, inside a file named write.js, we import writeStorage().

While in another file named read.js, we import readStorage().

And this is where the question rises,

Does imported functions from the same source, have access to their source global variables ?

i.e, can we modify STORAGE in index.js, using writeStorage() which we imported in write.js ?

and read STORAGE changes from read.js using readStorage() ?.

Solution

I want to provide clearer answer about that. There are two scopes for functions: lexical, and dynamic. Dynamic means, a function will search variables in the are, there it was called:

let someVar = 'global';

function dynamicScope () {
    someVar = 'dynamic';
    console.log(somevar);
}

dynamicalScope (); // will display 'global'

Lexical means, the function will seach variables where it was writted/delcared:

let someVar = 'global';

function lexicalScope () {
    someVar = 'lexical';
    console.log(somevar);
} 

lexicalScope(); // will display 'lexical'

But in JavaScript, there is no way to use dynamic scope, so all function will search variables where it has been declared/written.

DO NOT PAY ATTENTION ON DETAILS, IT’S JUST A PSEUDO-CODE.

Answered By – Azamat

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.