connie
connie

Reputation: 117

variable scope in javascript

    calValue: function (data) {
            var self = this;
            var values = data.values;
            for (var i = 0; i < data.length; i++) {
                  if(data.condition == 0){
                    (function (values) {
                            for (i = 0; i < values.length; i++) {
                            }
                    })(values)
                    }
                    else{
                            //do sth else
                    }
            }
    }

my understanding is each funtion has its own context and the variable being declared inside it, will only be effetive inside. Like above code snippet, i expect the "i" variable inside the inner for-loop won't impact the outer one "i" variable. However, the fact is it do affect.

Could someone please help explain? Thanks.

Upvotes: 1

Views: 46

Answers (1)

Pointy
Pointy

Reputation: 413717

With var declarations, scope is at the function level. Such declarations are interpreted as if they appeared at the very start of the enclosing function.

In modern JavaScript environments, the let declaration allows you to create variables scoped to local blocks of statements. (Also const for non-modifiable symbols.)

In your case, that inner i in the nested function just refers to that i declared externally. From inside a function, you can always "see" out, but you can't "see" in. That's how scope works.

Upvotes: 1

Related Questions