How to use Global Variables in jQuery - javascript

How can i take global variables in jQuery.
this syntax is right that I'm using.
var $val = 2;
or
val = 2; (without using var keyword).
Thnx.

First and foremost: Avoid using global variables whenever possible. It is (almost) always possible. (With apologies to the Dalai Lama)
But answering the question:
If you use var at global scope (outside of all functions), it creates a global variable.
If you just assign to a variable you haven't declared anywhere, if you're not using strict mode (and I recommend you do use it), it will create a global implicitly. This is The Horror of Implicit Globals and should be avoided.
If you really, really need to create a global variable without using var at global scope, you can do that without the Horror by explicitly using the window object:
window.val = 2;
But I reiterate my opening point: Avoid globals.
Here's one way to do that: Use a scoping function around all of your code:
(function() { // <== The start of the scoping function
// Your code here, `var`s here are global to *your* code but not actually globals
// ...
})(); // <== The end of the scoping function, and the () to call it immediately
You should avoid globals even within your code, but by using a scoping function, you at least protect yourself from the outside world (and vice-versa).

Related

Tune My Javascript

I have a JavaScript global Array, which I'm using in multiple functions. I heard that using global variables will give some performance headache. So, can anyone suggest me how I can avoid using global variable in this case?
var tpaArray = new Array();
In multiple functions, I am using and popping value from it.
[Note] In my code I am actually using multiple global variable and arrays
Global variables are not a performance problem. The problem with globals is that the global namespace is already very, very crowded, and so dumping your symbols there leads to the possibility of conflicting with something else.
It's almost always possible to avoid having globals. The usual way is to wrap all of your code in a scoping function:
(function() {
// Your code here
})();
Then you can have nested functions inside that function, and "globals" within that function that they all share.
(function() {
var someVar;
function foo() {
// You can use `someVar` here
}
function bar() {
// And also here
}
foo();
})();
That said, it's best to avoid having lots of shared variables or near globals, as it makes for writing functions with side-effects, which can be difficult to maintain.
If you have lots of variables, you can put them all into an object and pass this as an argument to each function. Then instead of accessing tpaArray, you'd access data.tpaArray, where data is the name of the argument.

Declaring Empty Variables to make them global

In a JavaScript environment can I declare a variable before a function to make the variable reachable on a global level.
For instance:
var a;
function something(){
a = Math.random()
}
Will this make "a" a global variable?
or is using...
var a = function(){
var b = Math.random();
return b;
}
document.write(a())
Really the only way to do it?
Is there a way to make "b" global other than calling the function "a()"?
There are basically 3 ways to declare a global variable:
Declaring it in the global scope, outside of any function scope.
Explicitly assigning it as a property of the window object: window.a = 'foo'.
Not declaring it at all (not recommended). If you omit the var keyword when you first use the variable, it'll be declared globally no matter where in your code that happens.
Note #1: When in strict mode, you'll get an error if you don't declare your variable (as in #3 above).
Note #2: Using the window object to assign a global variable (as in #2 above) works fine in a browser environment, but might not work in other implementations (such as nodejs), since the global scope there is not a window object. If you're using a different environment and want to explicitly assign your global variables, you'll have to be aware of what the global object is called.
Will this make "a" a global variable?
A var declaration makes the variable local to the enclosing scope, which is usually a function one's. If you are executing your code in global scope, then a will be a global variable. You could as well just omit the var, then your variable would be implicitly global (though explicit declaration is better to show your intention).
Is there a way to make "b" global other than calling the function "a()"?
Your b variable is always local to the function a and will never leave it, unless you remove the var.
Before you think of making a variable global scope, you should consider JavaScript global namespace pollution. The more global variables you declare, the more it is likely that you application will get into conflict with another application's namespace and break. As such, it is highly important minimize the number of global variables.

Is 'window' always on top of the scope chain in javascript?

I've seen global variables defined with window.global_name.
I wonder why not just using global_name even if this script will be run in closure.
UPD: seems like IE doesn't explicitly add it to the window object, when you declare it inside of a closure
The last object on the scope chain in any ECMAScript environment is always the global object. In browsers, window is to all intents and purposes the global object. If you want to access a property of the global object x or a global variable x (which are almost but not quite the same thing), you should explicitly qualify it with window.x to avoid the possibility of x being resolved as a property of another object on the scope chain, or globalObj.x if you care about portability to non-browser environments. You can get a reference to the global object from anywhere in ECMAScript 3 or non-strict ECMAScript 5 as follows:
var globalObj = (function() { return this; })();
window.x is safer than simply x if there might possibly be another x in the current or preceding scopes. That being said, even window isn't fool-proof because you could define a variable named window.
They have similar effects, but window lets you explicitly declare that you're deliberately using a global. Otherwise, the reader doesn't know whether it's a var further up the scope chain, you just forgot to declare it, etc.
Unless you introduce another scope, e.g. by wrapping your code in a function, window === this === <the global scope>
However, window and this have the advantage that you can use the array syntax (window['something']) so you can access globals even if you have their name only in a string without using evil things like eval.
The answer is yes. If you declare a variable without the var keyword (inside a function), the variable will become implicitely a member of the window object, that is automatically initialized by the browser.
Outside a function, with or without the var keyword, the variable becomes implicitely a member of the window object.

How can I set a Global Variable from within a function

How can I set a Global Variable from within a function?
$(document).ready(function() {
var option = '';
$("[name=select_option_selected]").change(function() {
var option = $(this).val();
alert(option); // Example: Foo
});
alert(option); // Need it to alert Foo from the above change function
});
Declare it outside the scope of your jQuery onready
var option = '';
$(document).ready(function() {
$("[name=select_option_selected]").change(function() {
option = $(this).val();
alert(option); // Example: Foo
});
alert(option); //This will never be "Foo" since option isn't set until that select list changes
});
if you want to initialize this to the current selected value try this:
var option = "";
var $select_option_selected = null;
$(function() {
$select_option_selected = $("[name='select_option_selected']")
$select_option_selected.change(function() {
option = $(this).val();
});
option = $select_option_selected.val();
});
The Bad Way
As the other answers point out, it's not a good idea to create global variables. And as they point out, you can create a global variable by:
Declaring variable outside of all functions
Initializing your variable without the var keyword
Or, declaring it as a property of the window object: window.options = 'blah';
Using jQuery's Data() Method
But there is a better way of creating a globally accessible value using jQuery (and other libraries). In jQuery, use the data() method to store values associated with DOM elements:
// store 'blah' at document root
$(document).data('mysite.option', 'blah');
// retrieve value
alert($(document).data('mysite.option'));
Notice "mysite"... it is a good idea to namespace your data keys for the same reason it is good to namespace global variables in javascript.
$(document).ready(function() {
var option = '';
$("[name=select_option_selected]").change(function() {
option = $(this).val(); //no declaration of new variable, JavaScript goes to what encloses the function
alert(option); // Example: Foo
});
alert(option); // Need it to alert Foo from the above change function
});
Are you sure you want to? global variables are generally to be avoided. In the browser, window is the global object, so if you do window.option = ..., then option will be available globally.
I highly recommend naming a global variable something more unique than "option", to avoid clobbering existing stuff.
Another option, which I also don't recommend: leave off var
myvariable = 'foo';
If myvariable has never been delcared before, it will be declared as a property on window, making it global. This is generally considered to be (very) bad practice however.
You can use the window. prefix to access a global variable from within the scope of a function
window.option = ...;
Two approaches not mentioned by anybody else, applicable when you: 1. don't have access to the global LexicalEnvironment,10.2.3 and 2. are trying to write code that you wish to support systems wherein a direct reference to the global object15.1 (such as window in the HTML DOM, or GLOBAL in Node[1]) isn't guaranteed:
Make an indirect15.1.2.1.1 call to eval, by wrapping it in a superfluous PrimaryExpression, thus: (1,eval)(...) (the digit and comma operator are meaningless) … and then calling the result thereof. This forces the code to be run in the global execution context.10.4.2
We can then declare10.5 a new variable in the global lexical environment, as suggested above; or, for that matter, do anything else that we desire within that environment:
function global_define(ident, value){
(1,eval) ("var "+ident+"; (function(v){ "+ident+" = v })") (value) }
To be less round-about (and, to boot, avoid the FUD-ridden eval call), we can directly access the global object and set a property4.2 on it, which will then be available as a global variable elsewhere in our code.[2]
Instead of taking the eval approach above and gaining access to the global object via code we've written in the global context, it turns out we can access the global object as the this value10.4.3 within any function that is called with null:
var global = (function(){ return this }).call(null)
global[ident] = value
Phew.
Okay, more reading, for those of you who haven't fainted from specification links and eval calls, yet:
#kangax covers all of the bases quite thoroughly. Seriously, read that if you have any questions I haven't answered here (including those relating to the all-important idiosyncrasies browser support!)
Obviously, the relevant sections of the ECMAScript 5 specification itself, to get an idea for how things are intended to work in an ideal world. No, really though; I know that specifications are a scary idea, but the ES (“JavaScript”) specifications are one of the easiest-to-read and most comprehensible specs I've ever seen. They're truly excellent. Of immediate note, and in no particular order,
10.4, Establishing an Execution Context: Covers how ‘global code’ and ‘eval code’ are handled, specifically.
10.2, Lexical Environments: These describe “where variables are stored.” (The ‘Global Environment’ of interest is one of these.)
10.1, Types of Executable Code: Covers what ‘global code’ and ‘Program’s are.
15.1, The Global Object: Unfortunately, far less relevant than its title makes it sound. Still worth a skim.
[1]: The discussion in other answers, suggesting that exports in Node.js and other CommonJS-compliant systems is somehow related to the global object, about which this question asks, is misleading. In terms of system-design, one might be better suited to using their environment's module tools than poking around on the global object … but that's a discussion for another Stack Overflow post. (=
[2]: For those of you following along in the spec, it's harder to demonstrate that property-members of the global object are accessible as Identifier dereferences. Start with 10.2.1.2 Object Environment Records and 10.2.3 The Global Environment to understand how the global object is linked to an environment, then hop on over to 18.12.3, 18.12.2, and 18.12.1 in that order, collectively describing [[Get]] on the global object.
Nota bene: At no point in this elaboration did I suggest that doing either of these things was a good idea. Or, for that matter, that interacting with the global scope at all is a good idea. Of no relation to the question at hand, but proffered to soothe my own conscience, I add that I wrap all of my own code in a IIFE beginning immediately at the top of the file; this, along with religious application of the var keyword, ensures that I never interact with JavaScript's handling of the global object at all. A huge mess, avoided. You should do that. I said so. I'm smart. (;
just declare a global object
var obj={};
function my_function()
{
obj['newVariable'] = 'someValue';
}
in this way i achieved global variable.
http://jsfiddle.net/Kba5u/
var foo = 'bar';
function changeFooToBaz(){
foo = 'baz';
}
// changeFooToBaz();
console.log(foo); #=> 'bar'
Now, uncomment the call to changeFooToBaz:
var foo = 'bar';
function changeFooToBaz(){
foo = 'baz';
}
changeFooToBaz();
console.log(foo); #=> 'baz'
changeFooToBaz has indeed changed the contents of foo, a variable that was declared at a higher scope than the function.

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.

Categories

Resources