Functions, Input and Output - tdkehoe/blog GitHub Wiki

Functions have inputs and outputs. How to get data or values into a function and how to return output can seem puzzling.

The following code takes a string ("My aunt Sally") and returns an acronym ("MAS").

var makeAcronym = function(stringToSplit) {

  var          i = 0,
  arrayOfStrings = stringToSplit.split(' ');

  while (i < arrayOfStrings.length) {
      arrayOfStrings[i] = arrayOfStrings[i].charAt(0).toUpperCase();
      i++;
  }
  return arrayOfStrings.join('');
};

console.log(makeAcronym("My aunt Sally"));

The program starts at the last line. It says to print ("console.log") something. It's not saying to print "makeAcronym("My aunt Sally")":

console.log("makeAcronym("My aunt Sally")");

It's saying to run the function makeAcronym using the parameter (argument) "My aunt Sally".

Everything in code is symbolizing something else. makeAcronym is replaced by the block of code between the curly brackets, in the function makeAcronym.

But how does the function input data? The function has an argument: stringToSplit. This argument is replaced by the argument "My aunt Sally". Now our code looks like:

var makeAcronym = function("My aunt Sally") {

  var          i = 0,
  arrayOfStrings = "My aunt Sally".split(' ');

  while (i < arrayOfStrings.length) {
      arrayOfStrings[i] = arrayOfStrings[i].charAt(0).toUpperCase();
      i++;
  }
  return arrayOfStrings.join('');
};

That's how we get values into a function. But my classmate Jenny Knuth says, "What happens in a function stays in a function." How do we get values out of a function?

return activates when the function finishes running. We can tell return to output a value. In this case, an array is returned and before it's returned the method join('') runs to concatenate the array.

Where does return send its values? It replaces makeAcronym("My aunt Sally"), i.e., the called function. Remember that a called function includes parentheses, i.e., function(). In other words, function() is replaced by the returned value, and you don't have to think about what was in the parentheses, because the parentheses are part of the function.

The join() method replaces the array with a concatenated string, so the output is MAS.