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
Sachin Jain
21.9k34 gold badges113 silver badges177 bronze badges
2 Answers 2
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
Abe Haskins
1,3781 gold badge7 silver badges9 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Sachin Jain
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.
Abe Haskins
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.
Sachin Jain
Thanks abeisgreat. But this question is just out of curiousity.
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
Konstantin Dinev
35k14 gold badges79 silver badges103 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js