简体   繁体   中英

javascript: creating a local scope of a global variable undefines it before it is set

I do not understand this behavior:

var a = 1;
console.log('a is undefined1:', a == undefined);
var a;

//iterate selected jQuery elements:
jQuery.each(this, function(index, htmlElement) {
    console.log('a is undefined2:', a == undefined);
    var a;

Returns :
a is undefined1: false
a is undefined2: true

If the last line (var a;) is commented out, this is returned :
a is undefined1: false
a is undefined2: false

I would expect always the latter output. What do I not know?

Thanks so much!

Putting var a inside a function creates a different a variable that is scoped to that function.

Since you don't assign a value to it, it is undefined.

When you comment it out, you are testing the outer a which has the value of 1.

Variables are hoisted. It doesn't matter where in a function you use var foo , the foo for that function still applies to the whole function.

Declaring variable within function using var makes local copy (new variable) with scope on the whole function - it does not matter whether it is used before it is declared.

Never declare variables without var .

If you want to access the golobal variable and you have local variable of the same name, you can access the global foo variable using window.foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM