Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Two separate scripts - share variables?

If I have two separate scripts in an HTML page with JavaScript are the variables shared between the entire page? Or only within their own declarations?

Example:

<script> var title = "Hello World!"; </script>
// random HTML/PHP
<script> document.write(title); </script>

Will that write "Hello World!"? This seems like bad coding convention how else could I achieve something like this with proper form.

like image 495
Bobby S Avatar asked Dec 01 '11 21:12

Bobby S


People also ask

How do you pass variables between two JavaScript files?

In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file.

Can you have two script tags?

An HTML page can contain multiple <script> tags in the <head> or <body> tag. The browser executes all the script tags, starting from the first script tag from the beginning.

Is var global in JavaScript?

The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.

How does var work in JavaScript?

var is the keyword that tells JavaScript you're declaring a variable. x is the name of that variable. = is the operator that tells JavaScript a value is coming up next. 100 is the value for the variable to store.


3 Answers

Variable title in your example is declared as a global variable, therefore it will be available to any and all scripts loaded into the same page. Whats more, if there is already a global variable named title on the same page, its value will be overwritten when you assign it the value "Hello World!"

The usual practice to avoid this sort of problem is to declare exactly one global variable, then put all of your other variables inside it. For example:

var bobbyS_vars = {
    title: "Hello World!";
};

Assign that lone global variable a name that no one else is likely to choose, such as your name or employer's name or best-of-all, a domain name that belongs you or your employer.

Another, more common way to handle this problem is to take advantage of of the way that JavaScript handles variable scope within functions. For example, create an anonymous function, declare all of your code inside that function, then call the function at the end of the declaration by putting () at the end of the declaration. For example:

(function() {
    var title = "Hello World!";

    document.write(title);
})();

// title is not in scope here, so it is undefined,
// unless it were declared elsewhere.

If you want to share some variables, but not others, have your anonymous function use a combination of approaches:

var bobbyS_vars = {
    title: "Hello World!";
};

(function() {
    var employeeId = "E 298";
    var count = 7;

    document.write("<p>" + bobbyS_vars.title + "</p>");
    document.write("<p>" + employeeId + "</p>");
})();

// At this point, bobbyS_vars.title is in scope and still has the 
// value "Hello World!". Variables employeeId and count are not
// in scope and effectively private to the code above.

One final note. All of the functions that your code declares are also effectively global variables. So, if you create a function named printTitle, it is 1) available to all other code on the page and 2) could overwrite or be overwritten by another function on the same page also named printTitle. You can protect and/or expose your functions the same way you would any other variable:

var bobbyS_vars = { };

(function() {
    // Private functions
    var function = addOne(i) {
        return i + 1;
    };

    // Public vars
    bobbyS_vars.title: "Hello World!";

    // Public functions
    bobbyS_vars.printTitle = function() {
        document.write("<p>" + bobbyS_vars.title + "</p>");
        document.write("<p>" + addOne(41) + "</p>");
    };
})();

// At this point, function addOne is not directly accessible,
// but printTitle is.
bobbyS_vars.printTitle();

Note that although function addOne is effectively a private function within the closure, it is still accessible indirectly, via the printTitle function because addOne and printTitle are both within the same scope.

like image 55
dgvid Avatar answered Oct 16 '22 11:10

dgvid


title is in the Global scope, which, in the case of JavaScript running in a web browser, is the window object. When you say var title = "Hello World!" outside of any function that would limit its scope, it is the same as saying window.title = "Hello World!".Your code is equivalent to this:

<script>
    window.title = "Hello World!";
</script> 
<!-- random HTML/PHP -->
<script>
    document.write(title);
    // or document.write(window.title) works just as well
</script> 
like image 28
gilly3 Avatar answered Oct 16 '22 12:10

gilly3


They will all be "shared" in accordance with scoping rules and such. Separate files has no effect on this EXCEPT the order of the inclusion of said files.

Edit: The same rule applies to inline scripts as well.

And to elaborate on the exception:

If I have file Foo where I declare the following:

var fooVar = barVar;

Then I have file Bar where I declare the following:

var barVar = 'bar';

And I include them in this order:

<script type="javascript/text" src="foo.js"></script>
<script type="javascript/text" src="bar.js"></script>

You will get a interpreted error because the use of barVar comes before its declaration.

like image 3
Matthew Cox Avatar answered Oct 16 '22 12:10

Matthew Cox