Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 579
Boris Avatar asked Dec 17 '10 15:12

Boris


People also ask

How do I use a variable from one file to another in JavaScript?

To import a variable from another file in JavaScript:Export the variable from file A , e.g. export const str = 'Hello world' . Import the variable in file B as import { str } from './another-file.

Can you include one JavaScript file in another?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

How is a variable accessed from another file?

The variable number is declared globally and may be accessed from other file when including its declaration with the “ extern ” prefix. However, the variable coefficient is only accessible from the file in which it is declared and only from that point on (it is not visible in function main .

How do I include an external JS file in another JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.


1 Answers

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.

like image 194
Joel Etherton Avatar answered Sep 30 '22 13:09

Joel Etherton