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.
Global keywords can be used to read or modify the global variable inside the function. Using a global keyword outside of the function has no use or makes no effect.
Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).
You can override global variable default values as follows: Deployment Level. If the Deployment Settable check box is selected at design time in the Global Variable editor, you can override at the deployment level.
Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function.
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);
}();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With