Frontend Development 17 min read

Best Practices for Writing High‑Quality JavaScript Functions: Naming, Comments, and Robustness

The article advises front‑end developers to improve JavaScript function quality by adopting clear, English‑style names, using consistent prefixes for visibility, writing informative comments such as JSDoc, and applying defensive programming techniques—including default parameters, try/catch, and granular promise error handling—to create maintainable, robust code.

vivo Internet Technology
vivo Internet Technology
vivo Internet Technology
Best Practices for Writing High‑Quality JavaScript Functions: Naming, Comments, and Robustness

This article continues the series "How to Write High‑Quality JavaScript Functions" (Part 1 introduced function execution mechanisms). It focuses on three core aspects of function quality: naming, commenting, and robustness.

1. Problems with current function naming

Many front‑end projects suffer from ambiguous or inconsistent function names. The author identifies three typical issues:

Differences between Chinese and English naming conventions.

Lack of multi‑dimensional thinking when improving name accuracy.

Insufficient use of auxiliary tools for name discovery.

These problems are illustrated with examples from React lifecycle methods such as componentDidMount and componentWillReceiveProps , explaining why the verbs did (past tense) and will (future tense) are used.

2. Giving function names an English style

The article recommends studying basic English grammar and borrowing naming patterns from open‑source projects. It also suggests using tools like Google Translate and codelf to search for naming conventions in existing code bases.

3. Example: a Ramda source function

var forEachObjIndexed = _curry2(function forEachObjIndexed(fn, obj) {
  var keyList = keys(obj);
  var idx = 0;
  while (idx < keyList.length) {
    var key = keyList[idx];
    fn(obj[key], key, obj);
    idx += 1;
  }
  return obj;
});
export default forEachObjIndexed;

The function name forEachObjIndexed is not self‑explanatory; the author advises adding clear comments to convey its purpose.

4. Prefixes and visibility

Because JavaScript lacks true private variables, developers often prepend _ or $ to indicate internal use only. The author classifies function names into two categories:

Functions not exposed to the outside (private).

Functions exposed to the outside (public API).

Special cases such as Symbol‑based names are also shown:

const ADD = Symbol('add');
[ADD](a, b) {
  console.log('a + b');
}

5. Importance of comments

Good comments improve readability and can generate online documentation. The article reviews several comment styles:

Egg.js style – simple and clean.

Lodash – not detailed in this article.

JSDoc – provides type information and parameter descriptions.

Apidoc – non‑intrusive, suitable for large projects.

Example of a JSDoc comment:

/**
 * add
 * @param {Number} a - number
 * @param {Number} b - number
 * @returns {Number} result - sum of two integers
 */
function add(a, b) {
  // FIXME: validate a and b types
  let result = a + b;
  return result;
}

6. Defensive programming and robustness

Robust functions should handle unexpected inputs and errors gracefully. The article demonstrates several techniques:

Default parameters (e.g., function print(obj = {}) ).

Destructuring with default values to avoid undefined . function print(obj = {}) { const { name = '未知姓名', age = '未知年龄' } = obj; console.log('name:', name); console.log('age:', age); }

Using try / catch for synchronous errors: try { throw new Error('hello godkun, i am an Error'); console.log('this line will not execute'); } catch (e) { console.log(e.message); }

Handling asynchronous errors with promises, async/await, or event‑based callbacks.

For complex promise chains, the author suggests attaching .catch after each step instead of a single final catch:

auth()
  .catch(goAuthErrorHandle)
  .then(getIP)
  .catch(goIPErrorHandle)
  .then(function (r) {});

This pattern prevents a failure in one stage from aborting the entire login flow.

7. Personal reflections on error handling

The author emphasizes tailoring error‑handling strategies to project importance, team skill level, and future maintainability. Over‑engineered solutions (e.g., using monads) may be powerful but can hinder readability for most teams.

Conclusion

Function naming, commenting, and defensive coding are essential for front‑end quality. By learning English grammar, leveraging tools, writing clear comments, and applying appropriate error‑handling techniques, developers can produce more maintainable and robust JavaScript code.

frontendJavaScriptbest practicescode commentsrobustnessfunction naming
vivo Internet Technology
Written by

vivo Internet Technology

Sharing practical vivo Internet technology insights and salon events, plus the latest industry news and hot conferences.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.