Why does this work in javascript?

2019-05-05 18:48发布

Just now,I saw some code like this:


if(condition){
    var xx='sss';   
}
//do something

if(condition){
    console.info(xx);
}

Now, I just wonder why the second if statement work? How can it access the xx variable since it is a local variable defined in another if statement?

7条回答
够拽才男人
2楼-- · 2019-05-05 19:27

If a variable is declared inside a conditional statement, it is still available anywhere following the declaration in the containing function (or globally if the conditional is not in a function). However, it will equal undefined if the condition evaluates to false, unless the variable is later assigned a value.

If a local variable is referenced globally or in another function, a JavaScript error will occur. Depending on your browser, the error may say the variable "is not defined" or "is undefined". This is different from the variable equaling undefined like mentioned above, because a variable that equals undefined can still be referenced.

查看更多
登录 后发表回答