Is it possible to define a global variable in a JavaScript function?
I want use the trailimage variable (declared in the makeObj function) in other functions.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
function makeObj(address) {
**var trailimage = [address, 50, 50];**
document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0" style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
obj_selected = 1;
}
function truebody() {
return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
function hidetrail() {
var x = document.getElementById("trailimageid").style;
x.visibility = "hidden";
document.onmousemove = "";
}
function followmouse(e) {
var xcoord = offsetfrommouse[0];
var ycoord = offsetfrommouse[1];
var x = document.getElementById("trailimageid").style;
if (typeof e != "undefined") {
xcoord += e.pageX;
ycoord += e.pageY;
}
else if (typeof window.event != "undefined") {
xcoord += truebody().scrollLeft + event.clientX;
ycoord += truebody().scrollTop + event.clientY;
}
var docwidth = 1395;
var docheight = 676;
if (xcoord + trailimage[1] + 3 > docwidth || ycoord + trailimage[2] > docheight) {
x.display = "none";
alert("inja");
}
else
x.display = "";
x.left = xcoord + "px";
x.top = ycoord + "px";
}
if (obj_selected = 1) {
alert("obj_selected = true");
document.onmousemove = followmouse;
if (displayduration > 0)
setTimeout("hidetrail()", displayduration * 1000);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<img alt="" id="house" src="Pictures/sides/right.gif" style="z-index: 1; left: 372px;
top: 219px; position: absolute; height: 138px; width: 120px" onclick="javascript:makeObj('Pictures/sides/sides-not-clicked.gif');" />
</form>
</body>
</html>
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>
Just declare
var trialImage;
outside. Then
function makeObj(address) {
trialImage = [address, 50, 50];
...
...
}
If you read the comments there's a nice discussion around this particular naming convention.
It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var declaration, and function declaration.
Here is the additional Wikipedia post that supports my point: Declarations and definitions
...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)
Just declare it outside the functions, and assign values inside the functions. Something like:
<script type="text/javascript">
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage = null ; // Global variable
function makeObj(address) {
trailimage = [address, 50, 50]; // Assign value
Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
function makeObj(address) {
trailimage = [address, 50, 50]; // Global variable, assign value
I hope this example explains more: http://jsfiddle.net/qCrGE/
var globalOne = 3;
testOne();
function testOne()
{
globalOne += 2;
alert("globalOne is :" + globalOne );
globalOne += 1;
}
alert("outside globalOne is: " + globalOne);
testTwo();
function testTwo()
{
globalTwo = 20;
alert("globalTwo is " + globalTwo);
globalTwo += 5;
}
alert("outside globalTwo is:" + globalTwo);
No, you can't. Just declare the variable outside the function. You don't have to declare it at the same time as you assign the value:
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
There are three types of scope in JavaScript:
Global Scope: where the variable is available through the code.
Block Scope: where the variable is available inside a certain area like a function.
Local Scope: where the variable is available in more certain areas, like an if-statement
If you add Var before the variable name, then its scope is determined where its location is
Example:
var num1 = 18; // Global scope
function fun() {
var num2 = 20; // Local (Function) Scope
if (true) {
var num3 = 22; // Block Scope (within an if-statement)
}
}
num1 = 18; // Global scope
function fun() {
num2 = 20; // Global Scope
if (true) {
num3 = 22; // Global Scope
}
}
It depends on what you intend by the word "global". If you want global scope on a variable for function use (which is what the OP wants) then you should read after the edit. If you want to reuse data from page to page without the use of a server, you should be looking to you use sessionStorage.
Session Storage
var Global = 'Global';
function LocalToGlobalVariable() {
// This creates a local variable.
var Local = '5';
// Doing this makes the variable available for one session
// (a page refresh - it's the session not local)
sessionStorage.LocalToGlobalVar = Local;
// It can be named anything as long as the sessionStorage
// references the local variable.
// Otherwise it won't work.
// This refreshes the page to make the variable take
// effect instead of the last variable set.
location.reload(false);
};
// This calls the variable outside of the function for whatever use you want.
sessionStorage.LocalToGlobalVar;
I realize there is probably a lot of syntax errors in this but its the general idea... Thanks so much LayZee for pointing this out... You can find what a local and session Storage is at http://www.w3schools.com/html/html5_webstorage.asp. I have needed the same thing for my code and this was a really good idea.
Scope
As of (I believe) 2015, a new "standard" for javascript (if you will) was introduced. This standard introduced many new ideas into javascript, one of them being the implementation of scope.
https://www.w3schools.com/js/js_scope.asp has all the details concerning this idea, but the cliff notes:
const defines a constant.
var has "global" scope.
let has "function" or "block" scope.
Classic example:
window.foo = 'bar';
A modern, safe example following best practice by using an IIFE:
;(function (root) {
'use strict'
root.foo = 'bar';
)(this));
Nowadays, there's also the option of using the WebStorage API:
localStorage.foo = 42;
or
sessionStorage.bar = 21;
Performance-wise, I'm not sure whether it is noticeably slower than storing values in variables.
Widespread browser support as stated on Can I use....
It is very simple. Define the trailimage variable outside the function and set its value in the makeObj function. Now you can access its value from anywhere.
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
...
}
Yes, You can. Just don't use var, don't use let. Just initialize variable and it will be automaticly assigned global:
function firstFunction() {
if (typeof(testVar) === "undefined") {testVar = 1;} //initializing variable if not initialized
testVar += 1;
console.log('Test variable inside 1st function: '+testVar);
}
function secondFunction() {
testVar += 1;
console.log('Test variable inside 2nd function: '+testVar);
}
firstFunction();
secondFunction();
testVar += 1;
console.log('Test variable outside: '+testVar);
Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var for use only within that function’s scope. If you declare a variable without using var, even if it’s inside a function, it will still be seen as global.
References = https://www.freecodecamp.org/news/global-variables-in-javascript-explained/
All variables declared without "var" or "let" or anything else preceding it like "const" are global. So ....
function myFunction(){
myVar = "value"; // myVar is a global variable and can be used anywhere inside <script> tags.
}
As an alternative to global vars, you may use the localstorage of browsers (if not using older versions). You can use upto 5MB of this storage.
The code would be
var yourvariablevalue = 'this is a sample value';
localStorage.setItem("yourKeyvariablename", yourvariablevalue);
and this can be retrieved any time, even after you leave and open it at another time.
var yourvariablevalue = localStorage.getItem("yourKeyvariablename");
Hope this would help you !
If you are making a startup function, you can define global functions and variables this way:
function(globalScope)
{
// Define something
globalScope.something()
{
alert("It works");
};
}(window)
Because the function is invoked globally with this argument, this is global scope here. So, the something should be a global thing.
Here is sample code that might can be helpful.
var Human = function() {
name = "Shohanur Rahaman"; // Global variable
this.name = "Tuly"; // Constructor variable
var age = 21;
};
var shohan = new Human();
document.write(shohan.name + "<br>");
document.write(name);
document.write(age); // Undefined because it's a local variable
Here I found a nice answer: How can one declare a global variable in JavaScript?
To use the window object is not a good idea. As I see in comments,
'use strict';
function showMessage() {
window.say_hello = 'hello!';
}
console.log(say_hello);
This will throw an error to use the say_hello variable we need to first call the showMessage function.
Here is another easy method to make the variable available in other functions without having to use global variables:
function makeObj() {
// var trailimage = 'test';
makeObj.trailimage = 'test';
}
function someOtherFunction() {
document.write(makeObj.trailimage);
}
makeObj();
someOtherFunction();
Related
here i am taking a input from a drop down form on a html page. And i am putting it in to a var called AM.
var e = document.getElementById("UserTimeAM");
function onChangeAM() {
var AM = e.value;
var text = e.options[e.selectedIndex].text;
console.log(AM, text);
}
e.onchangeAM = onChangeAM;
onChangeAM();
From there a fetch is called to an api and i am using the AM variable in it. But the issue is that when the site is being served it comes back with an error saying AM is not defined.
lowHigh.forEach(d =>{
let wDate = new Date(d.time).getUTCDate();
let AM_Hour = AM;
let PM_Hour = PM;
AM_Hour = ("0" + AM_Hour);
if(wDate == i+1)
{
if(tidedata1.innerHTML == "")
{
tidedata1.innerHTML = `${AM_Hour}: - ${d.value}m`
tidedata1Full.innerHTML = `${AM_Hour}:am - ${d.value}m`
}
else
{
tidedata2.innerHTML = `${PM_Hour}: - ${d.value}m`
tidedata2Full.innerHTML = `${PM_Hour}:pm - ${d.value}m`
}
}
})
I thought using var would mean it was a global so the variable could be passed in to different functions.
You just need to initialize the AM variable in the scope outside of your two functions to make it possible to use it in both
var AM;
var e = document.getElementById("UserTimeAM");
function onChangeAM() {
AM = e.value;
var text = e.options[e.selectedIndex].text;
console.log(AM, text);
}
e.onchangeAM = onChangeAM;
onChangeAM();
lowHigh.forEach(d =>{
let wDate = new Date(d.time).getUTCDate();
let AM_Hour = AM;
let PM_Hour = PM;
AM_Hour = ("0" + AM_Hour);
if(wDate == i+1)
{
if(tidedata1.innerHTML == "")
{
tidedata1.innerHTML = `${AM_Hour}: - ${d.value}m`
tidedata1Full.innerHTML = `${AM_Hour}:am - ${d.value}m`
}
else
{
tidedata2.innerHTML = `${PM_Hour}: - ${d.value}m`
tidedata2Full.innerHTML = `${PM_Hour}:pm - ${d.value}m`
}
}
})
The problem
In order to fully understand the differences between each of the identifiers (let, var, const) we first need to understand the concept of scope.
What is Scope?
Scope determines the accessibility or visibility of variables to JavaScript. There are three types of scope in JavaScript:
Global scope
Function (local) scope
Block scope (new with ES6)
- Global Scope
Variables declared outside a function are in the global scope.
Global variables can be accessed and changed in any other scope.
- Local Scope
Variables defined within a function are in local scope and are not accessible in other functions.
Each function, when invoked, creates a new scope, therefore variables with the same name can be used in different functions.
Reference: JavaScript: Var, Let, or Const? Which One Should you Use?
Example
var first = 123;
if(true) {
var second = 456;
}
function abc(){
var third = 789;
}
abc();
Note that first and second are inside global scope, and third is in function (local) scope, because its declared inside a function
Important note
Variables declared using the var keyword are either globally or functionally scoped, they do not support block-level scope. This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.
Example:
function DoSomething(){
if(true){ //Some condition [only example]
var example = 123;
}
console.log({example})
}
DoSomething()
If it had been declared as a let, it would not be visible, and would belong to the ({}) block of the if, example:
function DoSomething(){
if(true){ //Some condition [only example]
let example = 123;
}
console.log({example})
}
DoSomething()
In this example above, i'm using let, with will generate an error, that is a good thing to alert the programmer.
How to solve
Just as #HaimAbeles said, you just need to initialize the AM variable in the scope outside of your two functions to make it possible to use it in both
Example:
var AM;
var e = document.getElementById("UserTimeAM");
function onChangeAM() {
AM = e.value;
var text = e.options[e.selectedIndex].text;
console.log(AM, text);
}
e.onchangeAM = onChangeAM;
onChangeAM();
...
Hey so I have a function that takes a string from an input box and splits it up to numbers and letters, seen here:
function sepNsLs() {
"use strict";
var letterArray = [];
var numberArray = [];
separatorSpacerator();
var L = 0;
var listResult = document.getElementById("listInput").value;
var splitResult = listResult.split(separator.sep);
for (; L < splitResult.length; L++) {
if (isNaN(splitResult[L])) {
letterArray.push(splitResult[L]);
} else if (Number(splitResult[L])) {
numberArray.push(splitResult[L]);
}
}
}
My program has to pass through JSLint perfectly, meaning I need to use my functions in strict mode. I've only put them in strict mode now, meaning that my later functions that try to call the letterArray and numberArray that I declared and filled in the SepNsLs function no longer call those arrays and the arrays come up undeclared. Here's the code for one of them:
function addNumbers() {
"use strict";
var sum = 0;
var i = 0;
sepNsLs();
while (i < numberArray.length) {
sum = sum + Number(numberArray[i]);
i++;
}
As you can see, I call the sepNsLs function in the addNumbers function, but because of strict mode, I can't use the arrays sepNsLs creates. How do I fix this? Also, is there a website like the javascript beautifier that will fix my current code to fit strict mode conventions?
EDIT: Separator is declared a global variable here:
var separator = {
sep: 0
};
separatorSpacerator makes it so that if I choose to split my input strings at a space, the input box to tell my program to split at the spaces declares the word "Space" so I can see it is a space I'm splitting my string at.
function separatorSpacerator() {
"use strict";
var list = document.getElementById("listInput").value;
if (document.getElementById("separatorInput").value === "space") {
separator.sep = " ";
} else if (document.getElementById("separatorInput").value === " ") {
separator.sep = " ";
document.getElementById("separatorInput").value = "space";
} else {
separator.sep = document.getElementById("separatorInput").value;
}
if (list.indexOf(separator.sep) === -1) {
alert("Separator not found in list!");
clearResults();
}
}
I can't use the arrays sepNsLs creates. How do I fix this?
One way of fixing this would be to return arrays sepNsLs creates with e.g. a tuple - return [numberArray, letterArray]; , and then use it like:
a) es6 syntax:
var [numberArray, letterArray] = sepNsLs();
b) pre-es6 syntax:
var split = sepNsLs(),
numberArray = split[0],
letterArray = split[1];
Your addNumbers function should also probably return sum - otherwise, it doesn't produce any meaningful results as it stands.
Although not relevant to the question and is more of a matter of naming convention preference - you might want to explore on Hungarian notation and its' drawbacks.
Your problem is one of scope. When you try to access numberArray inside of addNumbers it doesn't exist.
You have a couple of options:
Make all the variables that need to be accessed in each function global.
Wrap all of your functions in an outer function and place the 'global' variables into that outer scope.
The better option is #2, because you won't actually be polluting the global scope with variables. And you can declare "use strict" at the top of the outer function and it will force everything in it into strict mode.
Something like this:
(function() {
"use strict";
// These are now in-scope for all the inner functions, unless redclared
var letterArray = [], numberArray = [], separator = {sep: 0};
function sepNsLs() {
// code goes here
}
function addNumbers(){
// code goes here
}
function separatorSpacerator(){
//code goes here
}
// ...more functions and stuff
// and then call...
theFunctionThatKicksOffTheWholeProgram();
}());
The variables letterArray and numberArray are declared local to the function sepNsLs, they are only accessed in that scope (strict mode or not). Here is an example:
function foo() {
var fooVar = 5;
console.log(fooVar);
}// fooVar get destroyed here
function bar() {
console.log(fooVar); // undefined because fooVar is not defined
}
foo();
bar();
A scope usually is from an open brace { to it's matching close brace }. Any thing declared inside a scope is only used withing that scope. Example 2:
var globalVar = 5; // belongs to the global scope
function foo() {
var fooVar = 6; // belongs to the foo scope
function bar1() {
console.log(globalVar); // will look if there is a globalVar inside the scope of bar1, if not it will look if there is globalVar in the upper scope (foo's scope), if not it will in the global scope.
console.log(fooVar); // same here
var bar1Var = 7; // belongs to bar1 scope
}
function bar2() {
var globalVar = 9; // belongs to the bar2 scope (shadows the global globalVar but not overriding it)
console.log(globalVar); // will look if there is a globalVar in this scope, if not it will look in one-up scope (foo's scope) .... untill the global scope
console.log(bar1Var); // undefined because bar1Var doesn't belong to this scope, neither to foo's scope nor to the global scope
}
bar1();
bar2();
console.log(globalVar); // prints 5 not 9 because the serach will be in foo's and the global scope in that order
}
foo();
What you need to do is to decalre the variables letterArray and numberArray where they can be access by both sepNsLs and addNumbers (one scope above both of them). Or return the value from sepNsLs and store it in a variable inside addNumbers. Like this:
function sepNsLs() {
// logic here
return numberArray; // return the array to be used inside addNumbers
}
function addNumbers() {
var arr = sepNsLs(); // store the returned value inside arr
for(var i = 0; i < arr.length; ... // work with arr
}
From the MDN description of Function:
Note: Functions created with the Function constructor do not create
closures to their creation contexts; they always are created in the
global scope. When running them, they will only be able to access
their own local variables and global ones, not the ones from the scope
in which the Function constructor was called. This is different from
using eval with code for a function expression.
I understand,
var y = 10;
var tester;
function test(){
var x = 5;
tester = new Function("a", "b", "alert(y);");
tester(5, 10);
}
test(); // alerts 10
Replacing the tester = new Function("a", "b", "alert(y);"); with tester = new Function("a", "b", "alert(x);");, I will get
// ReferenceError: x is not defined
But couldn't understand the author's line-
...they always are created in the global scope.
I mean how is the new Function("a", "b", "alert(y);"); nested within the test fn is in global scope?
In fact, accessing it from outside the test fn will simply result in
Uncought TypeError:tester is not a function
Please elucidate.
In your example, "created in the global scope" means that tester will not have closure over x from test:
function test(){
var x = 5;
tester = new Function("a", "b", "alert(x);"); // this will not show x
tester(5, 10);
}
When you new up a Function, it does not automatically capture the current scope like declaring one would. If you were to simply declare and return a function, it will have closure:
function test(){
var x = 5;
tester = function (a, b) {
alert(x); // this will show x
};
tester(5, 10);
}
This is the trade-off you make for having dynamically compiled functions. You can have closure if you write the function in ahead of time or you can have a dynamic body but lose closure over the surrounding scope(s).
This caveat doesn't usually matter, but consider the (slightly contrived) case where you build a function body as a string, then pass it to a function constructor to actually be evaluated:
function addOne(x) {
return compile("return " + x + " + 1");
}
function addTwo(x) {
return compile("return " + x + " + 2");
}
function compile(str) {
return new Function(str);
}
Because the function is instantiated by compile, any closure would grab str rather than x. Since compile does not close over any other function, things get a bit weird and the function returned by compile will always hold a closure-reference to str (which could be awful for garbage collection).
Instead, to simplify all of this, the spec just makes a blanket rule that new Function does not have any closure.
You have to create an object to expose via return inside the test() function for it to be global. In other words, add var pub = {} and name your internal functions as properties and/or methods of pub (for example pub.tester = new func) then just before closing test() say return pub. So, that way it will be publically available (as test.tester). It's Called the Revealing Module Pattern.
What it means is that inside the function you can only refer to global variables, as you've found. However, the reference to the function itself is still in the local scope where it was created.
I'm confused as to where the confusion is.
It says that the function will be in global scope...and therefore will only have access to its own scope and the global scope, not variables local to the scope in which it was created.
You tested it and it has access to its own scope and the global scope, not variables local to the scope in which it was created.
So where's the confusion?
Is it in your assigning of the function to the variable testing? testing is just a local variable with a reference to the function...that has nothing to do with the scope of the creation of the function.
Scope is lexical, and has to do with where the function is created, not what random variables a function reference happens to be assigned to at runtime. And the documentation is telling you that when you make a function this way it acts as if it was created in the global scope...so it's acting completely as expected.
Here's an illustration:
This:
var y = 10;
var tester;
function test()
{
var x = 5;
// 10 and errors as not defined
tester = new Function("console.log(y); console.log(x);");
}
Is similar to this:
var y = 10;
var tester;
function test()
{
var x = 5;
// also 10 and errors as not defined
tester = something;
}
function something()
{
console.log(y);
console.log(x);
}
NOT
var y = 10;
var tester;
function test()
{
var x = 5;
// 10 and 5...since x is local to the function creation
tester = function()
{
console.log(y);
console.log(x);
}
}
This is a simple script that'll log the content of text from a Photoshop file.
var numOfLayers = app.activeDocument.layers.length;
var resultStr = "";
doAllLayers();
alert(resultStr);
function addToString(alayer)
{
if (alayer.kind == "LayerKind.TEXT")
{
var c = alayer.textItem.contents;
resultStr += c;
}
}
// main loop
function doAllLayers()
{
for (var i = numOfLayers -1; i >= 0; i--)
{
var thisLayer = app.activeDocument.layers[i];
addToString(thisLayer);
}
}
It works fine but I really should be passing a string into the function to add to itself, however it works.
How does the scope of JavaScript allow this to happen? Are declared local variables still accessed by functions or is it another trick I'm missing?
Here are some basic rules to variable scoping in JavaScript:
If defined with the var keyword, the variable is function-scoped. That is, the variable will be scoped to either the closest containing function, or to the global context if there is no containing function.
Example:
// globally-scoped variable (no containing function)
var foo = 'bar';
function test() {
// function-scoped variable
var foo2 = 'bar2';
if (true) {
// still function-scoped variable, regardless of the if-block
var foo3 = 'bar3';
}
// see?
console.log(foo3); // --> 'bar3'
}
If defined with the let keyword (ES6+), then the variable is block-scoped (this behavior more closely resembles most other C-family syntax languages). Example:
// error: top level "let" declarations aren't allowed
let foo = 'bar';
function test() {
// block-scoped variable (function are blocks, too)
let foo2 = 'bar2';
if (true) {
// block-scoped variable (notice the difference
// from the previous example?)
let foo3 = 'bar3';
}
// uh oh?
console.log(foo3); // --> ReferenceError: foo3 is not defined
}
If defined with neither the var or let keywords (e.g., foo = bar), then the variable is scoped to the global context. Example:
// globally-scoped variable
foo = 'bar';
function test() {
// also globally-scoped variable (no var or let declaration)
foo2 = 'bar2';
if (true) {
// still a globally-scoped variable
foo3 = 'bar3';
}
}
test();
console.log(foo, foo2, foo3); // 'bar', 'bar2', 'bar3'
In all of these cases, functions defined within scope of a variable still have access to the variable itself (technically you're creating a closure, as the numOfLayers and resultStr variables are lexically in scope of your addToString and doAllLayers functions).
Please note that the scoping rules are technically a little more nuanced than this, but you're better off reading a more in-depth article at that point.
You have defined var resultStr = ""; outside function which is a global variable. you can access this global variable inside addToString() and start concatenating to it. Note that inside the method you have not declared var resultStr = ""; else it would have been a different variable local to that method.
I want to access global variable 'x' when it is over-ridden by same named variable inside a function.
function outer() {
var x = 10;
function overRideX() {
var x = "Updated";
console.log(x);
};
overRideX();
}
outer();
Jsbin : Fiddle to Test
I don't want to rename the inner 'x' variable to something else.
Is this possible ?
Edit: Edited question after abeisgreat answer.
You can use window.x to reference the globally scoped variable.
var x = 10;
function overRideX() {
var x = "Updated";
console.log(x);
console.log(window.x);
};
overRideX();
This code logs "Updated" then 10.
The global scope of your web page is window. Every variable defined in the global scope can thus be accessed through the window object.
var x = 10;
function overRideX() {
var x = "Updated";
console.log(x + ' ' + window.x);
}();