Functions with a purpose

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Functions with a purpose

Functions you create should have a singular purpose. When they have one purpose, you can tell what it does at a glance.

For example:

  • filter: filters an array
  • map: returns an another array with mapped values

Function names should begin with verbs

Verbs are action words. If your function begins with a verb, you’ll know what the function does.

Here are a few examples:

  • getAppleCount: gets the number of apples
  • createUser: creates a user for the app
  • nextSlide: selects the next slide
  • sayName: says the name of the user

Makes sense?

Commenting your functions

When you write a function, you want to write a comment to accompany the function. This comment helps you remember what the function is about.

You can use format called JSDoc to comment your functions. A JSDoc comment is a multi-line comment that begins with /** and ends with */

/**
 * JSDoc style comment!
 */

You want to document at least three things for each function:

  1. What the function does
  2. Parameters
  3. Return value

What the function does tells you what the function is about in a sentence.

/**
 * Gets the first player from an array of players
 */
function getFirstPlayer (players) {
  return players[0]
}

Parameters tell you more about the parameters used in the function. You want to document three things about each parameter:

  1. The type of each parameter
  2. The name of the parameter
  3. A description of the parameter

We annotate each parameter with @param.

/**
 * <Description of the function>
 * @param {type} param1 <Description of param1>
 * @param {type} param2 <Description of param2>
 */

Example:

/**
 * Gets the first player from an array of players
 * @param {Array} players Array of players
 */
function getFirstPlayer (players) {
  return players[0]
}

Return value tells you more about the value you returned from your function. We document the return value with @returns. Here, you want to document two things:

  1. The type of the value
  2. A description of the value
/**
 * <Description of the function>
 * @param {type} param1 <Description of param1>
 * @return {type} <Description of the returned value>
 */

Example:

/**
 * Gets the first player from an array of players
 * @param {Array} players Array of players
 * @returns {String} Name of the first player
 */
function getFirstPlayer (players) {
  return players[0]
}

This JSDoc comment might look like a big chunk of text here. But it is formatted nicely for you to read in most text editors. Here’s an example with VSCode:

A JSDoc comment in VSCode.