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 Arrays Methods: Part 3

Robert James
Robert James
20,491 Points

(a, b)

is anyone able to explain a little more what this (a, b); return a - b does when using fuctions!

Dont quite understand it

Thanks in advance!

2 Answers

Erick Bongo
Erick Bongo
8,539 Points

Say you had two different sums that you wanted to work out 1st sum is 5 - 3. 2nd sum is 10 - 2.

/*Here You create a function and give it two arguments.
 (a,b)  or (c,d)  or (one, two). 
These are just used to store some type of value
 later such as a = 5, b = 3 or c = 5, d = 3.*/

function subtract (a,b){

// In the actual function itself is where
// you tell the function what type of sum you 
//wish to calculate and store, so in this case 
//we tell the function we want to subtract the 
//value in b from the value that is held in a

return (a - b);
}

// The last part is where you would call the
// function and pass your chosen values to
// the function's arguments ()

// To work out the first sum you would write
subtract (5, 3);  

// For the second sum you would write

subtract (10,2);

//All together it would look like this

function subtract (a,b){
return (a - b);
};

subtract (5 - 3);
subtract (10 -2);

Note we can call the function as many times as we like placing different values in a & b to work out different values.

You have the following function:

function subtract(a,b) {
  return a - b;
}

This function is called subtract and takes two arguments - a and b. These two arguments are used inside the function as local variables when you perform the calculation a - b (so they only live inside the function and not before/after). This function returns a value (hence the return keyword inside the function). You could use this function to assign the return value to some other value like this:

var value = subtract(3,2);

If you used console.log(value), you would get 1.

Is this explaining what you were struggling with? Feel free to ask again if not.