Where do I declare global JavaScript variables in a web page? - javascript

Where do I need to place a snippet of JavaScript code that initializes a variable that must be visible to all code executed with the page? (For example, event handlers on elements will need to access this variable).

The only way to not have a global variable is to use the var keyword in the scope of a function. Anything else is a global variable.
(function() {
var local = 5;
})();
It doesn't matter if the function is a literal or function definition, it has to be some type of function.
Global variable examples:
1:
var global = 5;
The above is not in a function scope, therefore global even if var is used.
2.
(function() {
global = 5;
})();
In the above, no var was used, so it becomes an implied global.
3.
function foo(){}
foo was not defined inside of another function or assigned to a object key so its globally accessible.
4.
(function() {
var local = global = 5;
})();
When doing multiple assignments with var, only the first variable becomes local... so global is a global variable and equates to 5.
5.
window.foo = 5;
Prefixing window. is an explicit way of defining a global variable in the context of a browser.
6.
this.x = 5;
By default in browsers, this points to the DOMWindow unless you're in a method that's attached to an object which is not window. It's the same as #5. Note that if you use a method like XMLHttpRequest, the context is of the window.
7.
with ( window ) { name = 'john'; }
If you use the with statement and you dont reference an object that already has a property, a global variable is defined. It's best to avoid using the with keyword in general.
Conclusion:
Personally, I would keep my code in an anonymous function scope, and only explicitly declare globals when I need to.
(function() {
var governor = 'Schwarzenegger',
state = 'California';
window.president = 'Obama';
})();
In the above, I define governor and state variables and they are local to my function. I want to explicitly define president as a global variable. This way, I'm not confused about which variables I defined as globals or not, because I explicitly prefix them with window..

You can do it out of any function, or in a function without using the 'var' keyword. Assign it before any other scripts (very top of the page, likely) so the scripts can read the value.
You can also place it in an included JS file, but putting it right on the page is usually more usable as you can see the global values easily, and they can be modified for each page by the server-side code. Also try to prevent assigning global variables in the body, it may make confussions and will be harder to read.
<head>
<script>
var numberOfDucks = 1000; // Global
function some_function() {
// numberOfDucks is accessible here
alert (numberOfDucks);
// until you mask it by defining a local variable using the 'var' keyword
var myLocal = 0; // is a local
anotherGlobal = 0; // is a global
}
</script>
<script>
// potentially some other script
</script>
<script src="even_more_script.js">
</head>
Defining a global in a function (implied-global) is not a good idea because it will make a lot of confussion.

you could place that variable at the beginning of the page (in the global scope if you HAD to make it visible everywhere) but I suggest two things
1) since you have to open a script block, avoid to declare it inside the body of your page since scripts block rendering. So put it just before </head>
2) avoid to create a simple var but use a namespace instead so you reduce risks of identifier collision
<script>
var YOUR_APP_NS = {};
YOUR_APP_NS.yourvar = ....
</script>
this is a good practice in order to not polluting the global scope. If you need several public var in this way you could just write
YOUR_APP_NS.yourvar1 = ....
YOUR_APP_NS.yourvar2 = ....
YOUR_APP_NS.yourvarN = ....
but the global var is still 1

Declare the variable outwith of any of your functions, that way it becomes a global variable.
Here's an example of a global variable. The first function uses the global but the second function uses a local variable with the same name which masks the global.
var globalVar = 1;
function testFunc1 () {
globalVar = 2; //Updates the global variable
}
function testFunc2 () {
var globalVar = 5; // This variable masks the global and only updates within the scope of this function
globalVar = 3;
}
Also, you mentioned that the snippet must initialise the global before any other reference. For this I would suggest you place your script block or reference to your javascript file before any other javascript references in your element as possible. If you have other javascript files which are going to rely on the global variable then you may wish to ensure they do not load until the rest of the page has loaded first using the defer attribute. See the following:
<script src="dependant.js" type="text/javascript" defer="defer"></script>
Another option is to dynamically add your dependant scripts after your initial script has loaded. You can do this using something like jQuery as follows:
$(window).load( function() {
$.getScript('dependant.js');
});

<head>
<script>
var b = 0;
</script>
<script src="...">
</head>
<body>
...
</body>

Related

Why can't I access variables inside a function?

If functions are objects in javascript, why can't I access the function scope defined variables?
I understand that in the code:
// variable test assigned an anonymous function
var test = function(){
var x = 5;
};
console.log(test.x); // undefined
// Even when the function is explicitly named:
function test(){
var x = 5;
}
console.log(test.x); // undefined
I don't need to get this working or anything; I just need to understand why functions are like this.
Thanks.
This would be one way to accomplish what you are trying:
function test() {
this.x = 5;
}
var foo = new test();
console.log(foo.x);
Using var x rather than this.x just declares a local variable
I believe it is because those variables only exist within the scope of the function you have defined. Outside the scope of that function they do not exist.
They are the equivalent of private members in a class of an object oriented language.
Alternatively you could have
function test() {
this.x = 5;
}
var testInstance = new test();
console.log(test.x);
Functions are objects, but that doesn't mean that any variable declared inside the function becomes a property of that function object. In fact, that would be terrible because you wouldn't be able to run a function more than once (since the second time, the variables would start with different values).
You can assign a property to a function object like this:
var test = function () {};
test.x = 5
The variable is visible only in the function and it is possible to access it only within the function, you can use global variable and then edot it insode the function.
You have created Local variables. Local variable can only be accessed within the function.
Try to understand about Local & Global JavaScript Variables
Local JavaScript Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Local variables have local scope: They can only be accessed within the function.
function myFunction() {
var name = "roy";
// code here can use name
}
Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.
var name = "roy";
// code here can use name
function myFunction() {
// code here can use name
}
var someName = function(){var x ...} /// only has local scope.
What is the scope of variables in JavaScript?
Will describe it better than I can. Good job on being curious and motivated.

Javascript Global vs Local Scope

I'm currently trying to understand Javascript's interesting take on global vs local scope.
My question is that why would the following returns undefined?
var a = 100;
function local() {
if (false) {
var a = 50;
}
alert(a);
}
Additionally, I ran this:
var a = 100;
function local() {
alert(a);
}
The result was a resounding: 100.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
Because of hoisting.
It means every variable declaration get's popped to the top of the function so the actual code that runs is:
var a = 100;
function local(){
var a;
if (false)
a = 50;
alert(a);
}
It has very little to do with global VS. local, you simply hid the outer a variable with the inner a variable.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
No
Regarding the question in the comment "In the case that I want to revert to using a global variable in case the if condition fails (which I intentionally did), how can I do so? ":
You can use eval:
var a = 100;
function local() {
if (false) {
eval('var a = 50;');
}
alert(a);
}
Live DEMO
But you should not!
JavaScript has function scope, not block scope (as many other programming languages). That means regardless where the var statement occurs (in your case, an if-branch that is not even executed), it declares a variable a in the function's local scope. It shadows the global a variable, but since it has no value assigned it returns undefined.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
You can access the variable as a property of the global object (window in browser environments):
var a = 100; // global
function loc() {
var a = 50;
alert(window.a); // 100
alert(a); // 50
}
loc();
However, you will hardly use this. Global variables are to be avoided in general, and in case of name clashes you should simply rename your local variable (for readability and maintainability at least).
I know that if a variable is in defined inside a function using var, then it will have Local Scope.
I also know that any function has easy access to Global variable.
When I tested following in Console of Browser, first output was undefined.
It means that function nwf() was unable to access Global variable nw1
This is due to reference error which highlights importance of Strict Mode
To avoid such scenario, never re-declare and/or initialize any variable with same name inside and outside any function, just unlike following:-
var nw1 = 1; // var creates global scope outside function
function nwf() {
alert(nw1);
var nw1 = 2; // var creates LOCAL scope inside function
alert(nw1);
};
nwf();

How to declare global variables using JS

How to declare a global variable using JavaScript, whose life remain through out the HTML code?
Can we access the variable that we had declared in one script in another script?
"Don't do this" is the simple answer. Clogging the global scope is generally a bad thing, especially if you have to ask how (which usually means that you're asking because you think it's the easy solution, but it's almost certainly not the right one). What exactly are you trying to do?
If you really want to, either:
declare it outside of any function
don't use the var keyword
use window.variable = value
Declare a variable outside any function. It will be accessible in other scripts.
Global variables are declared by using either the var keyword outside of the scope of a function, by assigning a variable without using var, or by directly assigning a property of the window object.
<script>
var global1 = 'foo';
global2 = 'bar';
window.global3 = 'baz';
function f() {
var not_global;
}
</script>
Declare a variable in a script tag before your other scripts.
<script type="text/javascript">
var global = "hello world";
</script>
Declare your variable in a <script> tag, but make sure to place it within your <body> tag, or the browser may not execute it!
Alternatively you may use a cookie.
Any variable that is defined outside a function or a class is global variable in Javascript.
For example:
<script>
var itsAGlobalVariable;
function someMethod() {
var itsALocalVariable;
}
</script>
You mean something like this:
var Foo = {
Bar: Value
}
Then you can access to this like that:
Foo.Bar
You can also set values:
Foo.Bar = "fancy value"

javascript variable

do we have to declare js variable like this:
var x=5;
or just simple like this
x=5;
what is the differences?... will it effect the functionality of the variable?...
variable_name = 5 would always put the variable_name into the global object (which is window in a browser)
If you are in the global context (= not a function context) the two statements are basically the same. But if you are in a function context, var makes sure that this variable is only declared within the current context.
So for instance:
function foobar() {
bar = 55;
}
foobar();
window.bar === 55 // true
Better:
function foobar() {
var bar = 55;
}
window.bar === 55 // false
Conclusion: always use var within the context of a function. This avoids clobbering / overriding the global object with variables.
The var keyword limits the scope of the variable to the current function. Leaving it off makes a global. Globals are bad and should be avoided as they are a key source of race conditions and scripts interfering with each other.
x=5 means this variable (after execution) will become global and can be accessed by all other parts in your code(and also by other javascripts).
while var x=5 will be familiar only to the block which it was declared on, (and it's descendants)
Note that although x=5 will be global, it will become global only when this line is execute!
So if you place this inside a function, it will become global only after that function is called (for the first time).
It makes no difference - with the second one (x=5;) the variable is automatically declared if it does not yet exist.
I always use the first option however.

Do jQuery and JavaScript have different namespaces?

I have this code in jQuery..
$(document).ready(function(){
var fieldCounter = 0; ...
I have a jQuery function that increments this value.
This works, but I can't access this value on the page from a non-jQuery function? The reverse is also true, if I scope it in JavaScript e.g.
<script type="text/javascript">
var fieldCounter = 0;
I can access it from javascript but jQuery can't view it?
I'm probably doing something really dumb?
It has nothing to do with jQuery, but all with Javascript scope.
$(document).ready(function() {
var fieldCounter = 0;
});
fieldCounter is declared inside a function. Since Javascript has function scope, the variable is not visible outside the function.
BTW, jQuery is Javascript, they play by the same rules, they're not two different technologies.
Exhaustive answers can be found here: What is the scope of variables in JavaScript?
jQuery is not magic. It is a JavaScript library. Your issue is that you're defining a local variable inside a function. Due to the way JavaScript lexical scoping works, you can't access it outside that function (with the exception of closures, which does not apply here).
Most likely, you just want:
$(document).ready(function(){
fieldCounter = 0;
That will make it a global variable.
Edit: Note that using a namespace and/or declaring the global variable is cleaner, but not required.
Your problem in the first case is scope. By putting the var init inside a function declaration, you've scoped it to access inside that function.
Something else is going on in the second case; more code would be necessary to see what.
The global scope in Javascript is window. That means that when you declare variables directly in <script> tags, you can get them back by asking for window.variableName.
A common way to resolve these kinds of scoping issues is to create a namespace framework. If you do it right you can call myNamespace.subNamespace.variable and have full confidence that because it's explicitly scoped to window, you can get it back no matter where you are.
Remember that jQuery is built in Javascript. There's nothing special about it.
JavaScript has function scope.
var count = 8;
var myfunction = function() {
var newCount = count + 1;
};
alert(newCount); // undefined
it's because of the scope of javascript... try to read this
Variables declared inside jQuery code block will have local scope.If you need to access a variable both in local javascript function as well as jQuery code block then declare the variable at global level. Sample Code snippet :-
<script type="text/javascript" language="javascript">
var increment = 0;
$(document).ready(function() {
$("#button2").click(function() {
increment = increment + 1;
alert(increment);
});
});
function ClickMe() {
increment = increment + 1;
alert(increment);
}
</script>

Categories

Resources