开发者

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

开发者 https://www.devze.com 2023-02-22 23:39 出处:网络
I do not understand this behavior: var a = 1; console.log(\'a is undefined1:\', a == undefined); var a; //iterate selected jQuery elements:

I do not understand this behavior:

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

//iterate selected jQuery elements:
jQuery.e开发者_运维知识库ach(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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号