0

The following code works great. It pushes 10 unnamed functions into an array and then successfully executes the 7th item in the array.

var storeStuff = [];

for (let i = 0; i < 10; i++) {
    storeStuff.push(function() {
    console.log(i * i);
    });
}

storeStuff[6]();

However the test function above is tiny. If I had a large function with many lines of code I'd likely want to declare it outside of the push.

For example what if I wanted to push a previously defined function and later invoke it like the example below?

var storeStuff = [];

function externalFunction(temp) {
    console.log(temp * temp)
}

for (let i = 0; i < 10; i++) {
    storeStuff.push(externalFunction(i));
}

storeStuff[6]();

Unfortunately this doesn't work as written and everything I've tried crashed and burned. What am I getting wrong?

DR01D
  • 1,325
  • 15
  • 32

1 Answers1

1

Use function declaration as below

var storeStuff = [];

externalFunction = function(temp) {
    console.log(temp * temp)
}

for (let i = 0; i < 10; i++) {
    storeStuff.push(externalFunction);
}
storeStuff[6](6);
Vineesh
  • 3,762
  • 20
  • 37
  • You are absolutely correct! How does `storeStuff.push(externalFunction);` know to send the `i` counter to externalFunction? Why isn't it `storeStuff.push(externalFunction(i));` – DR01D Jul 10 '17 at 06:24
  • 1
    that you should pass when calling that function. May be the index you are using. Like storeStuff[6](6); storeStuff[7](7); etc – Vineesh Jul 10 '17 at 06:26