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.
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
titleon 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:
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:
If you want to share some variables, but not others, have your anonymous function use a combination of approaches:
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:
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.