1

How do i get the value of the global variable inside a scope . If i have the same name variable present in same scope .

<script>
var number =2;

var fun= function(numbs){
    console.log(number);
    //here it displays 2

    var number =numbs;
    console.log(number);
    //here it  displays 3


    console.log(number);
    //how do i get value of global variable here
}

fun(3);
</script>
2
  • IMHO it is poor form to use the same variable name in different scopes and try to reference the parent(s) scope(s). use var numbers = numbs; instead! Commented Jun 19, 2014 at 15:51
  • Did you run this before posting? The first line (// here it displays 2) actually displays undefined due to variable hoisting. Commented Jul 26, 2014 at 13:52

2 Answers 2

6

you should be able to call

window.number

A global variable is really just a property of the window object.

Sign up to request clarification or add additional context in comments.

Comments

1

Simply :

console.log(window.number);

From the MDN :

Global variables

Global variables are in fact properties of the global object. In web pages the global object is window, so you can set and access global variables using the window.variable syntax.

But you shouldn't have to do this. If you need to go around shadowing, you have a design problem and you should probably fix it.

Comments

Your Answer

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.