Boris
Boris

Reputation: 10244

Is it possible to declare a variable in one javascript file and use it in another one?

If I had one javascript file:

var myVariable = "Awesome variable";

and another javascript file:

function printMyVariable() {
    document.writeln(myVariable);
}

would the printMyVariable method be able to recognize myVariable? My guess in "No", because the myVariable scope isn't recognizable in the second javascript file. So, I was wondering if someone could explain to me what needs to be done to make the magic happen, if possible. :)

Thanks.

Upvotes: 6

Views: 2468

Answers (5)

Free Consulting
Free Consulting

Reputation: 4402

simple

JS has flat scope, there are global1 and local only. var uses current scope. Let var foo be in global scope -- you will get global variable assessible from any of files (there are no namespaces or modules).

further

There is a Global object, and the global var becomes a property of it. In the browser environment window implements Global, so your global var will have qualified name as window.foo.

"redeclaring"

/* 
assuming browser environment
execution flow: top to bottom 
first file: (actually doesnt matter, becase its flat)
*/
var foo = "bar";
// equivalent to 
window.foo = "bar";

// second file:
var foo = 42;
// redeclared? no, because equivalent statement is
window.foo = 42;

1 illustrative purpose only, see the second part.

Upvotes: 1

Hogsmill
Hogsmill

Reputation: 1574

As an old perlie, I would never use a variable starting with 'my' as a global variable - my = local in perl :-) I agree it's bad practice.

The way to think of this is not as seperate files, but as one big file of al the JavaScript files concatenated in order. The scope is the same as it would be in that file. Indeed, this is exactly what happens when you minify...

Upvotes: 0

Spiny Norman
Spiny Norman

Reputation: 8337

As long as you call the function in the second file after you include the first file, you should be fine. You introduce a global variable, which is assigned to the window object in the DOM, so after you include the first file, window.myVariable will be equal to "Awesome variable". As mentioned above, though, all of this is a very bad idea.

Upvotes: 0

Chandu
Chandu

Reputation: 82913

It is possible since myVariable will be defined @ global scope though its in a different file. However make sure printMyVariable function is called after the variable is defined (in terms of including the script tags.)

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37533

Yes, as long as the file with the variable declaration is included before the file that uses it since it's all parsed in the same chunk but in order.

This is an exceptionally bad practice though.

Upvotes: 5

Related Questions