How to declare global variables using JS - javascript

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"

Related

Not understanding the concept of local and global variables

Ok so just a quick one... I REAAAAAALLLLY am not understanding scope at all. Do some reason whenever I put a variable inside of a function it's undefined. It seems the only way it works it to declare it OUTSIDE of a function. So what gives? Am I simply misunderstanding the concept of local and global variables? Because it seems global variables are the only ones that work...
Edit:
Simple example...
let a = 'something';
function myFunction() {
// Code block
};
This works 👆
But the following gives me undefined variables:
function myFunction() {
let a = 'something';
// Code block
};
First lets take a look at the differences between local and global variables.
LOCAL VARIABLES - Any variable defined inside of a function or loop. If the variable is defined in a certain function/loop, it can only be accessed in that function/loop.
For example:
function number() {
let a = 0;
// Can access a here.
}
// Cannot access a here.
GLOBAL VARIABLES - Any variable that is not defined inside of any function or loop. These variables can be accessed anywhere.
For example:
let b = 0;
function number() {
// b can be accessed here.
}
// b can be accessed here.
The scope of a variable is where it can be accessed in. For ex, a scope of a local variable that is defined inside of function number() is the number() function since it can only be accessed there.
One more quick thing (Credit to Mikael Lennholm) var doesn't scope a variable to a loop (or any non-function statement block), it only scopes it to the current function. To scope a variable to any statement block you have to use let/const
Now let's look at your examples:
Here is the first example:
let a = 'something';
myFunction();
function myFunction() {
console.log(a);
};
That works fine, and that's what you said.
Here is the second example you said doesn't work:
function myFunction() {
let a = 'something';
console.log(a);
};
myFunction();
But, if you click the run button, you'll actually see it does work, it does get logged. If you after this go and check in the console what the variable a is of course it will be undefined, since a can be only accessed in the myFunction() function, and the console is not in that function.
You said that the script doesn't work, it's most probably because of something else (if it was because of this there would be an error in the console). You can try posting the website here and I can help you.
Hope this helped you :)
Global variables are variables that you have access to them anywhere in your codes.
Local variables are limited to their scopes like a function, module, class and etc.
if you define a local variable it can be accessible in the nested level like closures.
if you define a global variable and you define the same name as local variable , the local overwrite the global, then be careful.

Any way to access local scope variable in outer scope in Javascript?

Is there any way to make local scope variable accessible in outer scope without creating an object or without using 'this'?
Say,
function foo(){
var bar = 10;
}
Any way to make variable 'bar' available outside function 'foo' scope?
No. Simply you can't. Scope is scope. If you want to access outside, make it declare outside and use it.
That's how things designed. I don't suggest any crappy way to make it possible.
Assign the value to a property of the window object:
function foo(){
window.bar = 10;
}
console.log(window.bar); //10
EDIT:
Since you can't accept his answer, then no - what you're asking for is impossible. Only solution is to declare the variable in the global scope, then initialize it later.
You can't access local variable outside the function.
Following post might help you to understand scopes in more detail -
What is the scope of variables in JavaScript?
You can do something like this:
var myScopedVariables = function foo(){
var bar = 10;
return [bar];
}
console.log(myScopedVariables);

window.variableName

I am going through some code and at the beginning of the script we have var emailID = email. Later on, the code refers to emailID by going window.emailID. I am wondering what are the rules that allow you to refer to a variable by going window.variableName?
I cannot post my script online as it is directly related to my work and would violate my contract.
window.variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable. Using window. is not necessary but is frequently used as a convention to denote that a variable is global.
Globals are generally to be avoided. You should define variables within the scope of functions.
Global variables in JavaScript are attached to the "global object", which in a browser environment is aliased to window object - this is why you can refer to a global variable either as variableName or window.variableName.
It's also worth mentioning that using global variables in JavaScript is not considered good coding practice.
Here's a good and very detailed explanation.
window.myVar or window["myVar"] is an explicit way to refer to a global variable.
A variable is a global variable if it's declared outside of a function (with or without "var"), or if it's declared inside a function without using "var", or if it's declared as window.myVar or window["myVar"].
A variable is declared by either assigning a value to it, or by using the keyword var.
One case where it's useful to refer to a global variable as window.myVar is if you're inside a function that has a local variable called myvar. In that case, myVar refers to the local variable, while window.myVar refers to the global variable.
Global Variables in JavaScript
var no =10;
function getNo()
alert(no); // 10
}
getNo();
When a global variable is set, it's added to the window object!
var no =10;
function getNo()
alert(window.no); // 10
}
getNo();
We can direct set window variable.
function setNo(){
window.no=100;
}
function getNo()
alert(window.no); // 100
}
setNo();
getNo();
For pure theoretical explanations (as I encountered this "issue" myself) and easy to digest information you can look at the problem as this:
var myName = "Bob" equals to - globalObject(Window) = { myName: "Bob" }
so when you declare a variable, that variable name is passed to the window object as a property and it's value as a property value. That's why you can call the variable as an object method of the window object, basically.
It is used to define global variable in JavaScript.
globalVar = "Hello World";
function function1(){
alert(window.globalVar);
}
function1();
This will print "Hello World" in the popup.
function function1(){
globalVar = "Hello World";
alert(window.globalVar);
}function function2(){
alert(window.globalVar);
}
function1();
function2();
This will create two popups with value "Hello World", one from function1() and another from function2().
So, by using window we can call a variable from any scope in javascript.

When do I use var? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Variable Scope
My understanding it that with in a function if I use var then I have a local variable. If I do not delcare var I now have a global variable.
But what about oustide of functions, what effect does var have?
First of all, it's generally bad practice to use code outside of functions. If nothing else, wrap your code in anonymous functions:
(function(){
// code
})();
As for what effect var has, it "declares" a variable:
var foo;
alert(foo); // undefined;
vs:
alert(foo); // error: foo is not defined
The reason for this is that the above code is functionally identical to:
alert(window.foo);
without declaring the variable with var, you get a lookup error, the same as trying to access the property of any object that doesn't exist.
Note that one of the oddities of var is that all declarations are pulled to the top of the script, so this will work as well:
alert(foo); // undefined
var foo;
You will also have access to your variable in the window object (though you will also have this by setting the variable without var, e.g. just foo=42):
var foo;
for(var key in window){
// one of these keys will be 'foo'
}
It is good practice to always use var. Strictly speaking when you are already in the global scope you don't need to but for the sake of code maintainability you should.
Say you have:
foo = 'bar';
But later you decide you want to move this code into a function:
function doSomething() {
foo = 'bar'; // oops forgot to add var
}
If you forget to add a var statement you've just created an implicit global. Now if you create a new object in the global scope that is named foo they will cause conflicts with one another.
function doSomething() {
foo = 'bar'; // Implicit global
}
foo = 'baz';
doSomething();
console.log(foo); // Returns 'bar', not 'baz'
This kind of error is particularly insidious when you forget to use var on something like i in a for loop. Learning to use JSLint can help to avoid these and other problematic logic or syntax errors.
Your question is answered in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
Using var outside a function is
optional; assigning a value to an
undeclared variable implicitly
declares it as a global variable.
However, it is recommended to always
use var, and it is necessary within
functions in the following situations:
If a variable in a scope containing the function (including the global scope) has the same name.
If recursive or multiple functions use variables with the same name and> intend those variables to be local.
Failure to declare the variable in
these cases will very likely lead to
unexpected results.
I believe using var outside of a function works the same as not using var: you get a global. The exception to this would be if you are in a class or some other namespace structure, in which it will still define a variable in that locale
i believe you want to create a var whenever you are initializing a variable. As i've coded, when ever i need to initialize a variable, i start it with var. If you declare a variable without the word var, it's always global. If you declare a variable with var, inside a function, it's local to that function. If you create a variable with var outside functions, it will be a global variable.
If you are declaring a global variable and set a value it won't have any practical value, but as mentioned, it's best practice. If however you want to declare a variable without a value, you will need "var".

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

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>

Categories

Resources