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:
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 type of each parameter
The name of 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 type of 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: