0

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.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • possible duplicate of [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Evan Davis May 19 '15 at 21:10

4 Answers4

6

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);

        });

    }
2

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

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
2

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

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
2

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.

UsainBloot
  • 816
  • 6
  • 20