Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Numbers The Math Object

How to pass values and call a function stored in an array?

Hello!

If we can store a function in an array, how do we pass values into it, and how do we invoke this function?

var y = ['a string', 3, true, function(a, b) {return a + b;}]

5 Answers

Ethan Ferrari
Ethan Ferrari
3,017 Points

Ha, made that harder than it was. Don't code in bed. Here:

var myFunc = y[3];
myFunc(2,3);
//returns 5
Ethan Ferrari
Ethan Ferrari
3,017 Points

Try:

var myFunction = y[2]; myFunction.apply($someObject, [my,passed,arguments]);

I'm on the iPad now so can run it in he console... Let me know if that does the trick.

Hello Ethan,

var y = ['a string', 3,true, function(a,b){return a +b}]

You got me there, Im lost. I think my function stored in the array position 3 should receive 2 numbers into its parameters so that it can return the sum of these 2 numbers.

Not sure:)

You also can call a function directly from an array like this:

var y = ['a string', 3, true, function(a, b) {return a + b;}]

y[3](1,2);

thanks a million guys!! Now, I totally got it!!