Master Clean JavaScript: Variable & Function Best Practices for Readable Code

This article presents practical JavaScript guidelines for naming variables, structuring functions, and avoiding common pitfalls, illustrating each bad pattern with concise code examples and showing the improved, more readable alternatives to help developers write cleaner, maintainable code.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Master Clean JavaScript: Variable & Function Best Practices for Readable Code

Variables

Use semantic variable names Bad

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

Good

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

Use searchable names Bad

// 86400000 是什么鬼?
setTimeout(blastOff, 86400000);

Good

// Use a named constant.
const MILLISECONDS_IN_A_DAY = 86400000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY);

Use descriptive temporary variables Bad

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

Good

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

Avoid meaningless temporary variables in loops Bad

const locations = ['Austin', 'New York', 'San Francisco'];
locations.forEach((l) => {
  doStuff();
  doSomeOtherStuff();
  // ...
  // ...
  // ...
  // 等等 我忘记了l是啥了?
  dispatch(l);
});

Good

const locations = ['Austin', 'New York', 'San Francisco'];
locations.forEach((location) => {
  doStuff();
  doSomeOtherStuff();
  // ...
  dispatch(location);
});

Do not repeat information in object property names Bad

const Car = {
  carMake: 'Honda',
  carModel: 'Accord',
  carColor: 'Blue'
};
function paintCar(car) {
  car.carColor = 'Red';
}

Good

const Car = {
  make: 'Honda',
  model: 'Accord',
  color: 'Blue'
};
function paintCar(car) {
  car.color = 'Red';
}

Prefer default parameters over short‑circuit assignment Bad

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

Good

function createMicrobrewery(breweryName = 'Hipster Brew Co.') {
  // ...
}

Functions

Limit function parameters to two Bad

function createMenu(title, body, buttonText, cancellable) {
  // ...
}

Good

function createMenu({ title, body, buttonText, cancellable }) {
  // ...
}
createMenu({
  title: 'Foo',
  body: 'Bar',
  buttonText: 'Baz',
  cancellable: true
});

Follow the single‑responsibility principle Bad

function emailClients(clients) {
  clients.forEach((client) => {
    const clientRecord = database.lookup(client);
    if (clientRecord.isActive()) {
      email(client);
    }
  });
}

Good

function emailClients(clients) {
  clients
    .filter(isClientActive)
    .forEach(email);
}
function isClientActive(client) {
  const clientRecord = database.lookup(client);
  return clientRecord.isActive();
}

Make function names reflect their purpose Bad

function addToDate(date, month) {
  // ...
}
addToDate(date, 1);

Good

function addMonthToDate(month, date) {
  // ...
}
addMonthToDate(1, date);

Keep functions at a single level of abstraction Bad

function parseBetterJSAlternative(code) {
  const REGEXES = [/* ... */];
  const statements = code.split(' ');
  const tokens = [];
  REGEXES.forEach((REGEX) => {
    statements.forEach((statement) => {
      // ...
    });
  });
  const ast = [];
  tokens.forEach((token) => {
    // lex...
  });
  ast.forEach((node) => {
    // parse...
  });
}

Good

function tokenize(code) {
  const REGEXES = [/* ... */];
  const statements = code.split(' ');
  const tokens = [];
  REGEXES.forEach((REGEX) => {
    statements.forEach((statement) => {
      tokens.push(/* ... */);
    });
  });
  return tokens;
}
function lexer(tokens) {
  const ast = [];
  tokens.forEach((token) => {
    ast.push(/* ... */);
  });
  return ast;
}
function parseBetterJSAlternative(code) {
  const tokens = tokenize(code);
  const ast = lexer(tokens);
  ast.forEach((node) => {
    // parse...
  });
}

Remove duplicated code Bad

function showDeveloperList(developers) {
  developers.forEach((developer) => {
    const expectedSalary = developer.calculateExpectedSalary();
    const experience = developer.getExperience();
    const githubLink = developer.getGithubLink();
    const data = { expectedSalary, experience, githubLink };
    render(data);
  });
}
function showManagerList(managers) {
  managers.forEach((manager) => {
    const expectedSalary = manager.calculateExpectedSalary();
    const experience = manager.getExperience();
    const portfolio = manager.getMBAProjects();
    const data = { expectedSalary, experience, portfolio };
    render(data);
  });
}

Good

function showEmployeeList(employees) {
  employees.forEach((employee) => {
    const expectedSalary = employee.calculateExpectedSalary();
    const experience = employee.getExperience();
    let portfolio = employee.getGithubLink();
    if (employee.type === 'manager') {
      portfolio = employee.getMBAProjects();
    }
    const data = { expectedSalary, experience, portfolio };
    render(data);
  });
}

Avoid using Object.assign for default values Bad

const menuConfig = { title: null, body: 'Bar', buttonText: null, cancellable: true };
function createMenu(config) {
  config.title = config.title || 'Foo';
  config.body = config.body || 'Bar';
  config.buttonText = config.buttonText || 'Baz';
  config.cancellable = config.cancellable === undefined ? config.cancellable : true;
}
createMenu(menuConfig);

Good

const menuConfig = { title: 'Order', buttonText: 'Send', cancellable: true };
function createMenu(config) {
  config = Object.assign({
    title: 'Foo',
    body: 'Bar',
    buttonText: 'Baz',
    cancellable: true
  }, config);
  // ...
}
createMenu(menuConfig);

Avoid flags in function parameters Bad

function createFile(name, temp) {
  if (temp) {
    fs.create(`./temp/${name}`);
  } else {
    fs.create(name);
  }
}

Good

function createFile(name) {
  fs.create(name);
}
function createTempFile(name) {
  createFile(`./temp/${name}`);
}

Avoid side effects Bad

let name = 'Ryan McDermott';
function splitIntoFirstAndLastName() {
  name = name.split(' ');
}
splitIntoFirstAndLastName();
console.log(name);

Good

function splitIntoFirstAndLastName(name) {
  return name.split(' ');
}
const name = 'Ryan McDermott';
const newName = splitIntoFirstAndLastName(name);
console.log(name);
console.log(newName);

Avoid polluting global variables Bad

Array.prototype.diff = function (comparisonArray) {
  const hash = new Set(comparisonArray);
  return this.filter(elem => !hash.has(elem));
};

Good

class SuperArray extends Array {
  diff(comparisonArray) {
    const hash = new Set(comparisonArray);
    return this.filter(elem => !hash.has(elem));
  }
}

Prefer functional programming over imperative loops Bad

let totalOutput = 0;
for (let i = 0; i < programmerOutput.length; i++) {
  totalOutput += programmerOutput[i].linesOfCode;
}

Good

const totalOutput = programmerOutput
  .map(p => p.linesOfCode)
  .reduce((acc, lines) => acc + lines, 0);

Encapsulate conditional logic Bad

if (fsm.state === 'fetching' && isEmpty(listNode)) {
  // ...
}

Good

function shouldShowSpinner(fsm, listNode) {
  return fsm.state === 'fetching' && isEmpty(listNode);
}
if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
  // ...
}

Avoid negative‑named predicate functions Bad

if (!isDOMNodeNotPresent(node)) {
  // ...
}

Good

if (isDOMNodePresent(node)) {
  // ...
}

Avoid excessive conditional branching; use polymorphism Bad

switch (this.type) {
  case '777':
    return this.getMaxAltitude() - this.getPassengerCount();
  case 'Air Force One':
    return this.getMaxAltitude();
  case 'Cessna':
    return this.getMaxAltitude() - this.getFuelExpenditure();
}

Good

class Boeing777 extends Airplane {
  getCruisingAltitude() {
    return this.getMaxAltitude() - this.getPassengerCount();
  }
}
class AirForceOne extends Airplane {
  getCruisingAltitude() {
    return this.getMaxAltitude();
  }
}
class Cessna extends Airplane {
  getCruisingAltitude() {
    return this.getMaxAltitude() - this.getFuelExpenditure();
  }
}

Avoid premature micro‑optimizations; modern browsers handle many cases Bad

for (let i = 0, len = list.length; i < len; i++) {
  // ...
}

Good

for (let i = 0; i < list.length; i++) {
  // ...
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptcoding standardsvariable namingclean codefunction design
Tencent IMWeb Frontend Team
Written by

Tencent IMWeb Frontend Team

IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.

0 followers
Reader feedback

How this landed with the community

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.