Scope in Javascript: Why is the answer 10, not 20?

时间:2016-10-20 18:59:34

标签: javascript scope

I'm learning about scope in JS. I was just thinking that I'm getting the hang of it, when I came across this example:

var x = 20;

for (x = 0; x < 10; x++) {
}

// returns 10    
console.log(x);

Why 10? I would have expected 20 as an answer.

4 个答案:

答案 0 :(得分:1)

When you start your for loop, you are currently writing for (x = 0). This is overwriting the var x = 20 statement, so now x = 0. The loop continues to run as you would expect. When you use the var keyword, you are creating a new variable in that current scope. Because you are not initializing your for loop with the var keyword, basically, JavaScript looks for an existing variable called x. It finds the one you created with var x = 20 and will overwrite the reference, so now x = 0.

答案 1 :(得分:0)

In JavaScript (EMCA-Script < 6) you can only create scopes with functions. Any other language construct won't create scope:

for(var i = 0; i < 10; i++) {}

// Logs 10 because "i" in the for loop doesn't create
// a block scope so "i" is available after the whole loop
console.log(i);

Since you've already declared an x before your for loop, and the whole loop uses x from 0 to 10, because for block won't create a scope, it's absolutely right that you get 10.

Scopes with functions:

function doStuff() {
   // Inner scope
   var a = 10;
}

// Outer scope
var a = 20;

答案 2 :(得分:0)

It returned 10 because for loop changed it by incrementing. You didn't create new variable, so Javascript automatically overwrote already existing. This is because you created for loop, which has that variable as an initial expression. It happens when you want refer to a variable, that doesn't exist in lexical environment, syntax parser take it from outside. It means in this case, that from global object where you declared variable x. Then your loop changed that variable to 10.

I hope, I explained to you what happened. Please be understanding for me, I'm new here.

答案 3 :(得分:0)

x在开始时为20,然后您在for周期中更改其值。循环将其值更改为0,1,2,3,4,5,6,7,8,9,10。最后,您将获得10作为值,因此您遇到的结果实际上是预期结果。< / p>