Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access overridden global variable inside a function

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.

like image 700
Sachin Avatar asked Apr 05 '13 05:04

Sachin


People also ask

Can you read global variables inside of a function?

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.

Can global variables be changed inside a function?

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

Can we override global variables?

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.

Can functions access global variables C++?

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.


2 Answers

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.

like image 104
Abe Haskins Avatar answered Oct 05 '22 23:10

Abe Haskins


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);
}();
like image 35
Konstantin Dinev Avatar answered Oct 06 '22 01:10

Konstantin Dinev