Any way to access local scope variable in outer scope in Javascript? - 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);

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.

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.

Is it better to declare a function with or without var? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between using var and not using var in JavaScript
There are two ways I've seen people declare functions in javascript. Either:
foo = function()
{
//Do stuff
}
or
var foo = function()
{
//Do stuff
}
I'm new to javascript, and would like to know if there is a real difference between the two. Is one better to use than the other, or does it depend on the situation?
AFAIK, if you do not state var then your function will be assigned to the global scope (same scope level as the window object), however if you declare it as var it will be contained within its parent scope.
EDIT: to clarify after the response from Tomalak, the function will belong to its parent scope, however if the parent scope is a function which is executed, after execution of the enclosing function, any functions declared without var will be accessible within the global context.
There are two ways:
Declaring it in a variable
Using the default function declaration
In your case, you're trying to declare it in a variable. Declaring variables (whether function or not) start with the var syntax.
var foo = function() { }; // please note that semicolon (;)
When defining a function normally:
function foo() { }
So, again, in your case, the var is required, unless you pre-define it:
var foo;
foo = function() { };
Edit: As James stated, if you wish to define it in the global scope you can discard the var keyword. But to be honest it's still a better practise to predefine the variable if you wish to define it on another scope level.
It's better to declare with var, otherwise you may be affecting any other var within the global scope. Check for example this question for more information: What is the scope of variables in JavaScript?

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"

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".

Categories

Resources