A set of best practices for JavaScript projects

Vahid Panjganj
Aug 9, 2017 · 16 min read
Lego street art by Jan Vormann

Maintaining someone else’s code is not a smooth process. It takes time to observe the project (folder structure, naming, dependencies, scripts etc.), find the pattern and develop the new feature in harmony and consistency with the existing code. Different developers use different styles which are derived from their different tastes. They may work on a project together or pick up someone else’s work. Which in both cases, having a common ground is essential.

That’s why at Elsewhen we decided to come up with a set of common practices for everyone to follow. Maintenance is easier as it requires less time analysing the existing codebase to realise what’s going on. The result is a list of guidelines which looks random and is not perfect. But we try to stick to it and improve it by making it public. It covers various aspects of a project. A more detailed version is hosted on github in two languages, and constantly gets updated.

Project Guidelines:

Because while developing a new project is like rolling on a green field for you, maintaining it is a potential dark twisted nightmare for someone else. Here’s a list of guidelines we’ve found, written and gathered that (we think) works really well with most JavaScript projects.

1. Git

1.1 Some Git rules

There are a set of rules to keep in mind:

Because this way all work is done in isolation on a dedicated branch rather than the main branch. It allows you to submit multiple pull requests without confusion. You can iterate without polluting the master branch with potentially unstable, unfinished code. read more…

Because you can make sure that code in master will almost always build without problems, and can be mostly used directly for releases (this might be overkill for some projects).

Because it notifies team members that they have completed a feature. It also enables easy peer-review of the code and dedicates forum for discussing the proposed feature

Because rebasing will merge in the requested branch (master or develop) and apply the commits that you have made locally to the top of the history without creating a merge commit (assuming there were no conflicts). Resulting in a nice and clean history. read more ...

Just because

Because it will clutter up your list of branches with dead branches.It insures you only ever merge the branch back into (master or develop) once. Feature branches should only exist while the work is still in progress.

Because you are about to add your code to a stable branch. If your feature-branch tests fail, there is a high chance that your destination branch build will fail too. Additionally you need to apply code style check before making a Pull Request. It aids readability and reduces the chance of formatting fixes being mingled in with actual changes.

Because it already has a list of system files that should not be sent with your code into a remote repository. In addition, it excludes setting folders and files for most used editors, as well as most common dependency folders.

Because it protects your production-ready branches from receiving unexpected and irreversible changes. read more… Github and Bitbucket

1.2 Git workflow

Because of most of the reasons above, we use Feature-branch-workflow with Interactive Rebasing and some elements of Gitflow (naming and having a develop branch). You can read more about the steps we follow here.

2. Documentation

3. Environments

Because different data, tokens, APIs, ports etc… might be needed on different environments. You may want an isolated development mode that calls fake API which returns predictable data, making both automated and manually testing much easier. Or you may want to enable Google Analytics only on production and so on. read more...

Because you have tokens, passwords and other valuable information in there. Your config should be correctly separated from the app internals as if the codebase could be made public at any moment.

How? use .env files to store your variables and add them to .gitignore to be excluded. Instead, commit a .env.example which serves as a guide for developers. For production, you should still set your environment variables in the standard way. read more here by Rafael Vidaurre.

3.1 Consistent dev environments:

Because it lets others know the version of node the project works on. read more…

Because any one who uses nvm can simply use nvm use to switch to the suitable node version. read more...

Because some dependencies may fail when installed by newer versions of npm.

Because it can give you a consistent environment across the entire workflow. Without much need to fiddle with dependencies or configs. read more…

Because it lets you share your tooling with your colleague instead of expecting them to have it globally on their systems.

3.2 Consistent dependencies:

Because you want the code to behave as expected and identical in any development machine read more here by Kent C. Dodds.
Use package-lock.json on npm@5 or higher. Alternatively you can use Yarn. For older versions of npm, use —save --save-exact when installing a new dependency and create npm-shrinkwrap.json before publishing. read more...

4. Dependencies

Because you may include an unused library in your code and increase the production bundle size. Find unused dependencies and get rid of them.

Because more usage mostly means more contributors, which usually means better maintenance, and all of these result in quickly discovered bugs and quickly developed fixes.

Because having loads of contributors won’t be as effective if maintainers don’t merge fixes and patches quickly enough.

Because dependency updates sometimes contain breaking changes. Always check their release notes when updates show up. Update your dependencies one by one, that makes troubleshooting easier if anything goes wrong. Also, you can use a cool tool such as npm-check-updates to keep track of dependency updates (Thanks to Raine Rupert Revere).

5. Testing

Because while sometimes end to end testing in production mode might seem enough, there are some exceptions: One example is you may not want to enable analytical information on a 'production' mode and pollute someone's dashboard with test data. The other example is that your API may have rate limits in production blocks your test calls after a certain amount of requests.

Because you don’t want to dig through a folder structure to find a unit test. read more…

Because some test files don’t particularly relate to any specific implementation file. You have to put it in a folder that is most likely to be found by other developers: __test__ folder. This name: __test__ is also standard now and gets picked up by most JavaScript testing frameworks.

because you want to test a business logic as separate units. You have to “minimize the impact of randomness and nondeterministic processes on the reliability of your code”. read more…

A pure function is a function that always returns the same output for the same input. Conversely, an impure function is one that may have side effects or depends on conditions from the outside to produce a value. That makes it less predictable read more…

Because it brings a certain level of reliability to your code. read more here by Preethi Kasireddy.

Because you don’t want to be the one who caused production-ready branch build to fail. Run your tests after your rebase and before pushing your feature-branch to a remote repository.

Because it’s a handy note you leave behind for other developers or DevOps experts or QA or anyone who gets lucky enough to work on your code.

6. Structure and Naming

// Bad
.
├── controllers
| ├── product.js
| └── user.js
├── models
| ├── product.js
| └── user.js
// Good
.
├── product
| ├── index.js
| ├── product.js
| └── product.test.js
├── user
| ├── index.js
| ├── user.js
| └── user.test.js

Because instead of a long list of files, you will create small modules that encapsulate one responsibility including its test and so on. It gets much easier to navigate through and things can be found at a glance.

Because when you break down a config file for different purposes (database, API and so on); putting them in a folder with a very recognizable name such as config makes sense. Just remember not to make different config files for different environments. It doesn't scale cleanly, as more deploys of the app are created, new environment names are necessary. Values to be used in config files should be provided by environment variables. read more here by Fedor Korshunov.

Because it’s very likely that you end up with more than one script, production build, development build, database feeders, database synchronization and so on.

Name it what you like, dist is also cool. But make sure that keep it consistent with your team. What gets in there is most likely generated (bundled, compiled, transpiled) or moved there. What you can generate, your teammates should be able to generate too, so there is no point committing them into your remote repository. Unless you specifically want to.

Then you can expect what component or module you will receive by simply just importing its parent folder.

7. Code style

Because this is all up to you. We use transpilers to use advantages of new syntax. stage-2 is more likely to eventually become part of the spec with only minor revisions.

Because breaking your build is one way of enforcing code style to your code. It prevents you from taking it less seriously. Do it for both client and server-side code. read more…

because we simply prefer eslint, you don't have to. It has more rules supported, the ability to configure the rules, and ability to add custom rules.

Because Flow introduces few syntaxes that also need to follow certain code style and be checked.

Because you don’t have to pollute your code with eslint-disable comments whenever you need to exclude a couple of files from style checking.

Because while it’s normal to disable style check while working on a code block to focus more on the logic you should remember to remove those eslint-disable comments and follow the rules.

Because then you can remind yourself and others about a small task (like refactoring a function, or updating a comment). For larger tasks use //TODO(#3456) which is enforced by a lint rule and the number is an open ticket.

Because your code should be as readable as possible, you should get rid of anything distracting. If you refactored a function, don’t just comment out the old one, remove it.

Because while your build process may(should) get rid of them, your source code may get handed over to another company/client and they may not share the same banter.

Because it makes it more natural to read the source code.

Because it makes it more natural to read the source code.

8. Logging

Because while your build process can(should) get rid of them, you should make sure your code style check gives you warning about console logs.

because it makes your troubleshooting less unpleasant with colorization, timestamps, log to a file in addition to the console or even logging to a file that rotates daily. read more…

9. API

Because we try to enforce development of sanely constructed RESTful interfaces, which team members and clients can consume simply and consistently. Lack of consistency and simplicity can massively increase integration and maintenance costs. Which is why API design is included in this article.

Because this is a very well-known design to developers (your main API consumers). Apart from readability and ease of use, it allows us to write generic libraries and connectors without even knowing what the API is about.

Because it reads better and keeps URLs consistent. read more…

Because plural may look nice in the URL but in the source code, it’s just too subtle and error-prone.

/students/245743
/airports/kjfk
GET /blogs/:blogId/posts/:postId/summary

Because this is not pointing to a resource but to a property instead. You can pass the property as a parameter to trim your response.

Because if you use a verb for each resource operation you soon will have a huge list of URLs and no consistent pattern which makes it difficult for developers to learn. Plus we use verbs for something else

/translate?text=Hallo

Because for CRUD we use HTTP methods on resource or collection URLs. The verbs we were talking about are actually Controllers. You usually don't develop many of these. read more...

Because if this is a JavaScript project guideline, Programming language for generating JSON as well as Programming language for parsing JSON are assumed to be JavaScript.

Because your intention is to expose Resources, not your database schema details

GET: To retrieve a representation of a resource.
POST: To create new resources and sub-resources
PUT: To update existing resources
PATCH: To update fields of existing resources.
DELETE: To delete existing resources

Because this is a natural way to make resources explorable.

http://api.domain.com/v1/schools/3/students

When your APIs are public for other third parties, upgrading the APIs with some breaking change would also lead to breaking the existing products or services using your APIs. Using versions in your URL can prevent that from happening. read more…

{
"code": 1234,
"message" : "Something bad happened",
"description" : "More details"
}

Because developers depend on well-designed errors at the critical times when they are troubleshooting and resolving issues after the applications they’ve built using your APIs are in the hands of their users.

Because most API providers use a small subset HTTP status codes. For example, the Google GData API uses only 10 status codes, Netflix uses 9, and Digg, only 8. Of course, these responses contain a body with additional information.There are over 70 HTTP status codes. However, most developers don’t have all 70 memorized. So if you choose status codes that are not very common you will force application developers away from building their apps and over to wikipedia to figure out what you’re trying to tell them. read more…

GET /student?fields=id,name,age,class

Sources: RisingStack Engineering, Mozilla Developer Network, Heroku Dev Center, Airbnb/javascript, Atlassian Git tutorials, Apigee, Wishtack and Medium.

Awesome Icons by icons8

Well, that’s it folks :). I know it is very opinionated, please feel free to challenge it in the comments. Checkout the repo if you have time, open an issue, make a pull requests.

You can follow me, here. You can also follow @elsewhen where we tweet about tech, product and design related stuff.


Elsewhen

Thoughts from the team at Elsewhen

Vahid Panjganj

Written by

Front-end Engineer @elsewhen (http://www.elsewhen.co)

Elsewhen

Elsewhen

Thoughts from the team at Elsewhen

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade