-
Notifications
You must be signed in to change notification settings - Fork 7
Best practice for writing a function
Kato Charles edited this page May 27, 2019
·
1 revision
- The name should be the shortest form of a verb/phrase that is representative of what the function/method should do.
e.g If you are creating a function that returns a plural of a given word,
pluralize()
, if you are creating a function that returns the nth term of the Fibonacci sequence,getNthTerm()
- You want to give context as to exactly what the method is to achieve. To do that we use the JSDoc format as given below:
/**
* Brief description of what a method is to do.
*
* @param {dataType} argumentName description of the argument
*
* @returns {dataType} returnVariable description of the return variable
*/
e.g
/**
* This method returns the nth term of the Fibonacci sequence
*
* @param {number} index index nth term
*
* @returns {number} term nth term
*/
getNthTerm(index: number): number {...}
Note that there should be a blank line between doc types to ensure readability
There should be a new line after declaring variables in a function and a new line before return statements. There can and should also be blank lines between logical chunks of code
within the function. Empty first lines within functions are, however, disallowed. This is to allow easy readability. See the example below to get more context:
const generateUrlWithQuery = (url: string, queryParams: object = {}) => {
const queryKeys = Object.keys(queryParams);
let endpoint = `${url}?`;
if (queryKeys.length > 0) {
queryKeys.forEach((key) => {
endpoint = `${endpoint}${key}=${queryParams[key]}&`;
});
}
return endpoint.substr(0, endpoint.length - 1);
};