A
A
Akaero2018-02-08 15:56:08
JavaScript
Akaero, 2018-02-08 15:56:08

Why is the loop variable declared without var?

In the guides, the loop variable is always declared (except for the before declaration) with var
Here is an example:

for (var i in obj) {
    result += obj_name + "." + i + " = " + obj[i] + "<br>";
  }

In Flanagan's book, an example is this:
function extend(o, p) {
    for(prop in p) { 
    o[prop] = p[prop]; 
    }
    return o;
}

Question: why is prop specified without var? It becomes a property of the global object, right?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly Zharov, 2018-02-08
@Akaero

1) examples in books are synthetic (it works fine)
2) true

P
Padre, 2018-02-08
@yii16

In general, var should be set only when the variable is first specified and only in strict mode, in other cases the interpreter will correct this error within itself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question