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

Basic question about parameters

This is from a challenge on another site, but my question is about programming.

How does JavaScript know what the parameter "a" is? Is there code missing here when "a" is defined by the user, say by .prompt()?

var puzzlers = [
  function ( a ) { return 3*a - 8; }, 
  function ( a ) { return (a+2) * (a+2) * (a+2); }, 
  function ( a ) { return a * a - 9; },
  function ( a ) { return a % 4; }
];

1 Answer

a is defined when the function is called. The syntax in this case would look like this:

puzzlers[0](3);

That would call the first function in the array, and set a to 3. So 3 would be multiplied by 3, and 8 would be subtracted from the result, and the answer, in this case, would be 9. In this particular array, you could call any of the functions by replacing the 0 in my example with any number 0 - 3, and you could replace 3 with anything you want, and it will be assigned to a. The following example calls the 3rd function in the array and assigns a to 8:

puzzlers[2](8);

As previously stated, that code would call the 3rd function in the array, and assign a to 8, so 8 would be multiplied by 8 and 9 would be subtracted from the product, so the function would evaluate to 55.