Alexander Mills
Alexander Mills

Reputation: 99960

Undefined value in forEach loop

I have this key in an JavaScript object {}

  resolve: function () {

        var result = this.initialValue;

        console.log('initial value:',result);  // 5

        this.functions.forEach(function (element, index) {

            console.log('index:', index, 'result:',result); //index=0, result=undefined :(
            var result = element.func(result);

        });

    }

result is defined outside the loop (with a value of Number(5)). But upon the first iteration of the loop, the result variable becomes undefined. Is there something about JS that I don't know?

Is the var result = element.func(result); call somehow redefining result in a weird way? No, that can't be, because that call comes after the first logging of result.

in this case element.func() is simply a variable representing console.log()

so element.func(result) should be equivalent to console.log(result), but it's printing out undefined instead of 5.

No idea what's going on.

Upvotes: 0

Views: 6668

Answers (4)

UsainBloot
UsainBloot

Reputation: 816

I believe that because of the var result inside of the forEach(function()) that result is being hoisted up to the console.log

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

Removing the var from inside the loop will fix the issue.

Upvotes: 2

Phiroze Noble
Phiroze Noble

Reputation: 303

There is a duplicate variable declaration inside the scope of the function. It's logging that variable before it's even defined.

Try getting rid of the 'var' and log it after you reassign it.

resolve: function () {

        var result = this.initialValue;

        console.log('initial value:',result);  // 5

        this.functions.forEach(function (element, index) {


            result = element.func(result);
            console.log('index:', index, 'result:',result);

        });

    }

Upvotes: 7

Cjmarkham
Cjmarkham

Reputation: 9681

You are re-assigning the result variable within the forEach loop.

var result = element.func(result);

So when the loop continues after the first time result will be element.func(result) and not this.initialValue

Upvotes: 2

Evan Davis
Evan Davis

Reputation: 36592

in your console.log, result refers to the local variable result, so it is undefined (as you define it on the next line.)

Upvotes: 2

Related Questions