Variables

Use meaningful and pronounceable variable names

Bad:

  1. const yyyymmdstr = moment().format('YYYY/MM/DD');

Good:

  1. const currentDate = moment().format('YYYY/MM/DD');

Use the same vocabulary for the same type of variable

Bad:

  1. getUserInfo();
  2. getClientData();
  3. getCustomerRecord();

Good:

  1. getUser();

Use searchable names

We will read more code than we will ever write. It’s important that the code we
do write is readable and searchable. By not naming variables that end up
being meaningful for understanding our program, we hurt our readers.
Make your names searchable. Tools like
buddy.js and
ESLint
can help identify unnamed constants.

Bad:

  1. // What the heck is 86400000 for?
  2. setTimeout(blastOff, 86400000);

Good:

  1. // Declare them as capitalized named constants.
  2. const MILLISECONDS_IN_A_DAY = 86400000;
  3. setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

Use explanatory variables

Bad:

  1. const address = 'One Infinite Loop, Cupertino 95014';
  2. const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
  3. saveCityZipCode(address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2]);

Good:

  1. const address = 'One Infinite Loop, Cupertino 95014';
  2. const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
  3. const [, city, zipCode] = address.match(cityZipCodeRegex) || [];
  4. saveCityZipCode(city, zipCode);

Avoid Mental Mapping

Explicit is better than implicit.

Bad:

  1. const locations = ['Austin', 'New York', 'San Francisco'];
  2. locations.forEach((l) => {
  3. doStuff();
  4. doSomeOtherStuff();
  5. // ...
  6. // ...
  7. // ...
  8. // Wait, what is `l` for again?
  9. dispatch(l);
  10. });

Good:

  1. const locations = ['Austin', 'New York', 'San Francisco'];
  2. locations.forEach((location) => {
  3. doStuff();
  4. doSomeOtherStuff();
  5. // ...
  6. // ...
  7. // ...
  8. dispatch(location);
  9. });

Don’t add unneeded context

If your class/object name tells you something, don’t repeat that in your
variable name.

Bad:

  1. const Car = {
  2. carMake: 'Honda',
  3. carModel: 'Accord',
  4. carColor: 'Blue'
  5. };
  6. function paintCar(car) {
  7. car.carColor = 'Red';
  8. }

Good:

  1. const Car = {
  2. make: 'Honda',
  3. model: 'Accord',
  4. color: 'Blue'
  5. };
  6. function paintCar(car) {
  7. car.color = 'Red';
  8. }

Use default arguments instead of short circuiting or conditionals

Default arguments are often cleaner than short circuiting. Be aware that if you
use them, your function will only provide default values for undefined
arguments. Other “falsy” values such as '', "", false, null, 0, and
NaN, will not be replaced by a default value.

Bad:

  1. function createMicrobrewery(name) {
  2. const breweryName = name || 'Hipster Brew Co.';
  3. // ...
  4. }

Good:

  1. function createMicrobrewery(name = 'Hipster Brew Co.') {
  2. // ...
  3. }