How to Declare a Global Variable in a .Js File

How to declare a global variable in a .js file

Just define your variables in global.js outside a function scope:

// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file
function testGlobal () {
alert(global1);
}

To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:

<html>
<head>
<!-- Include global.js first -->
<script src="/YOUR_PATH/global.js" type="text/javascript"></script>
<!-- Now we can reference variables, objects, functions etc.
defined in global.js -->
<script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
</head>
[...]
</html>

You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.

Define a global variable in a JavaScript function

As the others have said, you can use var at global scope (outside of all functions and modules) to declare a global variable:

<script>
var yourGlobalVariable;
function foo() {
// ...
}
</script>

(Note that that's only true at global scope. If that code were in a module — <script type="module">...</script> — it wouldn't be at global scope, so that wouldn't create a global.)

Alternatively:

In modern environments, you can assign to a property on the object that globalThis refers to (globalThis was added in ES2020):

<script>
function foo() {
globalThis.yourGlobalVariable = ...;
}
</script>

On browsers, you can do the same thing with the global called window:

<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>

...because in browsers, all global variables global variables declared with var are properties of the window object. (The new let, const, and class statements [added in ES2015] at global scope create globals that aren't properties of the global object; a new concept in ES2015.)

(There's also the horror of implicit globals, but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's "use strict".)

All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window, and window is already plenty crowded enough what with all elements with an id (and many with just a name) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name on there).

Instead, in modern environments, use modules:

<script type="module">
let yourVariable = 42;
// ...
</script>

The top level code in a module is at module scope, not global scope, so that creates a variable that all of the code in that module can see, but that isn't global.

In obsolete environments without module support, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:

<script>
(function() { // Begin scoping function
var yourGlobalVariable; // Global to your code, invisible outside the scoping function
function foo() {
// ...
}
})(); // End scoping function
</script>

Global variables in Javascript across multiple files

You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.

<script type='text/javascript' > 
var myFunctionTag = false;
</script>
<script type='text/javascript' src='js/helpers.js'></script>
...
<script type='text/javascript' >
// rest of your code, which may depend on helpers.js
</script>

Getting global Javascript variable in another Javascript file

Make it global;

script1.js

 var foobar = "O HAI";

script2.js

  alert(foobar);

Access Global variable from a .js file

Firstly, that's invalid syntax for declaring a function. You need braces:

function CreateVariables() {
glVarMsg3="Global variable";
}

Secondly you can either set an src or script content, but not both. So you'd need:

<script src="Test.js"></script>
<script>
CreateVariables();
console.log(glVarMsg3);
</script>

A good place to start would be this MDN article on functions. Additionally, I hope this is just for learning/testing as the use of document.write and global variables in this way is discouraged.

Is it bad practice declaring global variables in a.js file?

At least it's not a good practice, you could use an immediated invoked function expression:

(function() {
var x;
var y;

window.init = function(xValue, yValue) {
x = xValue;
y = yValue;
}

window.doWhateverYouWant = function() {
console.log(x + y);
}
}());

You could use this pattern unless you need access your global variable outside this .js file, when an cross-accessing between .js files or <script> elements are required, global variable is a simple solution (although you could use AMD or sth else instead).

Javascript: How to pass global variables/constant variable across different .js file

You can define directly on window object like

window.GAME_WIDTH = 800;
window.GAME_HEIGHT = 600;

and use this in index.js directly like window.GAME_WIDTH -= 100; no need to import anything if you are setting these global level.

Create a global variable in TypeScript

Okay, so this is probably even uglier that what you did, but anyway...

but I do the same so...

What you can do to do it in pure TypeScript, is to use the eval function like so :

declare var something: string;
eval("something = 'testing';")

And later you'll be able to do

if (something === 'testing')

This is nothing more than a hack to force executing the instruction without TypeScript refusing to compile, and we declare var for TypeScript to compile the rest of the code.

Is it possible to make global Variable in JAVASCRIPT?

Within the global scope (aka "window"), variables are global.

Check this out:

//this is global because it is in the global scope (the window)
var foo = 'stuff';
//because it is global (window) you can also access it like this:
console.log(window.foo); //'stuff'

Now you can access foo anywhere. It's worth noting that globals aren't best practice - so check out Object Oriented Programming (SOLID principles).

If you are within another scope (like a function) and don't use the var keyword to create a variable, the variable will be global:

function someFunction() {
someVariable = 'stuff'; //this created a global variable! (or references an existing one)
//you could also assign it to window:
window.someVariable = 'stuff';
//both are the same thing!
}

Inline js (onclick in your html) is not a good practice. Instead, you can follow the good practice and use javascript to register the click event:

//get reference to button
var myBtn = document.getElementById('myBtn');

//add click function
myBtn.addEventListener('click', function(event) {
myFunction();
});

function myFunction() {
console.log(foo); //'stuff'
}

Here's a demo of all of this: http://jsbin.com/OmUBECaw/1/edit

Just note that you'll need to get the element references after they are loaded into the dom. It's best practice to include your scripts just before the end of the body rather than in the head, like this:

  <!-- scripts here! -->
<script></script>
</body>

If you must keep the scripts in the head, then you'll need to put your javascript code in a function to run onload of the window:

window.addEventListener('load', function() {
//code here!
});


Related Topics



Leave a reply



Submit