Coding with JavaScript For Dummies
Book image
Explore Book Buy On Amazon

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.

 Get the total


 

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.

 Get the sum


 

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.

About This Article

This article is from the book:

About the book authors:

Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?

This article can be found in the category: