7

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.

asked Apr 5, 2013 at 5:43

2 Answers 2

3

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.

answered Apr 5, 2013 at 5:44
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah..But that won't work everytime. Imagine a case when the whole above code is inside another function. Then window.x won't work. And I will face the same issue.
Then it will depend on the specific case, however, I would suggest getting in the habit of naming your variables more clearly. Having several variables named the same thing (especially single characters) gets very confusing.
Thanks abeisgreat. But this question is just out of curiousity.
1

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);
}();
answered Apr 5, 2013 at 5:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.