The Benefits of Using Functions to Code with JavaScript

By Chris Minnick, Eva Holland

Using functions to code with JavaScript can be very useful to a programmer. Here is a program that adds numbers together. It works great and does exactly what it’s supposed to do, using a for……in loop.

<html>
<head>
 <title>Get the total</title>
</head>
<body>
 <script>
 var myNumbers = [2,4,2,7];
 var total = 0;
 for (oneNumber in myNumbers){
  total = total + myNumbers[oneNumber];
 }
 document.write(total);
 </script>
</body>
</html>

If you had multiple sets of numbers to add together, however, we’d need to write a new loop statement specifically for each new array of numbers.

This code turns the program from the code above into a function and then uses that function to find the sums of the elements in several different arrays.

<html>
<head>
 <title>Get the sum</title>
</head>
<body>
 <script>
  /**
 *Adds elements in an array
 *@param {Array.<number>} numbersToAdd
 *@return {Number} sum
 */
 function addNumbers(numbersToAdd) {
  var sum = 0;
  for (oneNumber in numbersToAdd) {
  sum = sum + numbersToAdd[oneNumber];
  }
  return sum;
 }
 var myNumbers = [2,4,2,7];
 var myNumbers2 = [3333,222,111];
 var myNumbers3 = [777,555,777,555];
 var sum1 = addNumbers(myNumbers);
 var sum2 = addNumbers(myNumbers2);
 var sum3 = addNumbers(myNumbers3);
 document.write(sum1 + “<br>“);
 document.write(sum2 + “<br>“);
 document.write(sum3 + “<br>“);
 </script>
</body>
</html>
JSDoc Tag Explanation
@author Programmer’s name
@constructor Indicates that a function is a constructor
@deprecated Indicates the method is deprecated
@exception Describes an exception thrown by a method; Synonymous with
@throws
@exports Specifies a member that is exported by the module
@param Describes a method parameter
@private Indicates a member is private
@return Describes a return value. Synonymous with @returns
@returns Describes a return value. Synonymous with @return
@see Records an association to another object
@this Specifies the types of the object to which the keyword this refers within a function
@throws Describes an exception thrown by a method
@version Indicates the version number of a library

The block comment that precedes the function above follows the format specified by the JavaScript documenting system, JSDoc. By commenting your functions using this format, you not only make your programs much easier to read, you also can use these comments to automatically generate documentation for your programs.

Functions are a great time, work, and space saver. Writing a useful function may initially take longer than writing JavaScript code outside of functions, but in the long term, your programs will be better organized, and you’ll save yourself a lot of headaches if you get into the habit of writing functions.