JavaScript Best Practices

JavaScript Clean Code — Name and Test Heuristics

Spread the love

Bad code has lots of unique characteristics. In this article, we’ll look at each one and what they are. We look at more general code smells.

In this article, we’ll look at how to name things properly, and to write a test that has high coverage and fast.


Use Long Names for Long Scopes

If the scope is long then the name should be longer than if they’re in a short scope.

Variables with short names lose their meaning over long distances.

Avoid Encodings

Names shouldn’t be encoded with scope information. We should avoid useless prefixes.

However, types in names can be useful in JavaScript since variables and constants have dynamic types.

Names Should Describe Side Effects

If a piece of code commits side effects, the name should reflect it. For example, if we have the following function:

let foo;  
const getFoo = () => {  
  if (!foo) {  
    foo = {}  
  return foo  

Then we should name it getFoo because we didn’t describe the obvious side effect in the name.

Instead, we should name it setFooIfNotExistAndGetFoo to take both actions into account.


Insufficient Tests

We should make sure that we have sufficient test coverage so that we know the code and branches work.

Also, our tests should take into account both positive and negative cases.

Boundary and edge cases should also have tests to test cases that may break our code.

Use a Coverage Tool

Test coverage tools tell us what we have tests for and what still needs test coverage.

They also tell us which branches of our code have test coverage.

Don’t Skip Trivial Tests

They’re easy to write and serves as good documentation.

An Ignored Test is a Question About an Ambiguity

An ignored test is always questionable. We don’t know why they’re skipped so we sure make the reason clear why we skip a test.

Test Boundary Conditions

Testing boundary conditions is important since code often breaks around boundary conditions.

Exhaustively Test Near Bugs

If a piece of code has bugs, then we should test those cases more.

Patterns of Failures are Revealing

Patterns that test cases fail can tell us a lot about what’s breaking our code.

Cases that fail tell usually have some pattern, like when they fail with 5 or more characters passed in or something like that.

Tests Should be Fast

Slow tests are torture to run. They just get ignored and won’t get run. We should make them as fast as possible, especially since there’s going to be lots of them.


We should name things in an unambiguous way. If there’re side effects, then we should describe them.

Also, tests should cover bugs and boundary cases and they should run fast.

We can use a coverage tool to get a clear idea of what pieces of code are covered by tests.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *