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 arraymap: 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 applescreateUser: creates a user for the appnextSlide: selects the next slidesayName: 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:
- What the function does
- Parameters
- 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:
- The
typeof each parameter - The
nameof the parameter - 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:
- The
typeof the value - 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:
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson