Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable difference between function scope javascript

I am reading the topics about the execution context and scope of javascript.Below is a simple code:

 var scope="global";  
    function t(){  
        alert(scope);  // alert :"undefined"
        var scope="local" ; 
        alert(scope);  // alert: "local"
    }  
    t();  

If I remove 'var scope="local" ; ' ,it becomes this:

var scope="global";  
function t(){  
    alert(scope);  // alert :"global"   
}  
t();  

I don't understand why the value of scope is changed to "global" in the second case after I remove var scope="local" in the function t().

Could someone help to explain this, thank you!

like image 498
Steven Liang Avatar asked Mar 05 '26 10:03

Steven Liang


2 Answers

When you do this:

scope = 'global'
function t() {
  alert(scope) // undefined
  var scope = 'func'
  alert(scope) // func
}
t()

at the line var scope..., you're telling js: watch out, I'm defining 'scope' in this function. So JS resets it's value (undefined). It's like if you did:

scope = 'global'
function t() {
  var scope; // erase previous 'scope', so it is now undefined
  alert(scope) // undefined
  scope = 'func'
  alert(scope) // func
}
t()

But if you just do

scope = 'global'
function t() {
  alert(scope) // global
}
t()

You're not creating the variable scope in your function, so JS does not erase it's value, and when you try to access it, JS tries to find it higher (in the global namespace in this case)

Hope you get it... It indeed a bit weird, because first, JS looks for every variable you are declaring in you function (and reset/initialise them) and then run your function.

Matt

like image 169
math2001 Avatar answered Mar 08 '26 00:03

math2001


Essentially, in your first example, the scope of scope (i.e. the var declared inside the function) is the entire body of the function t. It doesn't have a value until it gets to the var scope == ... line, but it is defined from the beginning.

So alert(scope) is resolve "scope" as the locally defined variable, that does not yet have a value - that is, it's undefined.

See this question

The benefits of declaring variables at the top of the function body in JavaScript

for more explanation.

like image 26
Tim Avatar answered Mar 08 '26 00:03

Tim