Why does this work in javascript?

2019-05-05 18:54发布

问题:

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?

回答1:

var in JavaScript is scoped to the containing execution context (e.g., the whole function's scope, or the whole global scope if the var is at global scope), not the block. JavaScript doesn't (yet) have block scope (ECMAScript6 looks likely to add it, via the new let keyword).

The code you've quoted is exactly equivalent to this:

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

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

This is covered by Section 10.5 of the specification, which describes what the engine does when entering a new execution context. (It's basically a two-phase process, first setting up all the declarations, and then executing step-by-step code.)

More: Poor misunderstood var



回答2:

In JavaScript the scope is exacted to the closure (the last enclosing function block, or defaults to the window object). When a variable is declared anywhere within that function block it is hoisted to the top of the scope, so in essence a variable exists as undefined starting at the very top of the scope if it is declared anywhere in the scope.

Think of it like this, when the code begins executing it scans all the instructions for declarations and allocates the symbol name starting immediately.

console.log(x);  // undefined
console.log(y);  // error: Uncaught ReferenceError: y is not defined
var x;

for that matter you can take it to extremes:

console.log(x);  // undefined, not an error

while (false) {
  if (false) {
    var x;
  }
}

even though var x can't possibly be reached, and during execution would be optimized away completely. the engine will still hoist the variable to the top of the scope

hope this helps -ck

useful link: http://www.youtube.com/watch?v=taaEzHI9xyY&feature=youtu.be#t=42m57s



回答3:

var declarations affect the entire scope of the smallest containing function or program. JavaScript is not block scoped.

Crock says:

Variable Declarations

All variables should be declared before used. JavaScript does not require this, but doing so makes the program easier to read and makes it easier to detect undeclared variables that may become implied globals. Implied global variables should never be used.

The var statements should be the first statements in the function body.

It is preferred that each variable be given its own line and comment. They should be listed in alphabetical order.

var currentEntry; // currently selected table entry
var level;        // indentation level
var size;         // size of table

JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.

Use of global variables should be minimized. Implied global variables should never be used.

Note, this is changing with the let statement, and in current JavaScript (EcmaScript 5), the variable name in a catch block is block scoped.



回答4:

javascript doesn't have block scope, so var xx='sss' is either locally scoped (if your sample code is inside a function) or globally scoped (if your sample code is not contained in a function).



回答5:

JavaScript is a dynamic language, that isn't always picky about things like variable scoping. So, this "feature" allows you to write the code

if (condition) {
    var xx = 'sss';
} else {
    var xx = 'ttt';
}

// do something

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

I would recommend avoiding this, since it makes your program harder to understanda and reason about.



回答6:

If you declare a variable using var within a function, the variable is scoped to within that function. An if statement is not a function.

I'm assuming in this case both if statements are within the same function and therefore xx is in scope?



回答7:

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.