{"id":18419062,"url":"https://github.com/kazuma512/clean-code-javascript","last_synced_at":"2025-06-21T04:37:38.651Z","repository":{"id":176410986,"uuid":"648981290","full_name":"kazuma512/clean-code-javascript","owner":"kazuma512","description":"Clean-code-javascript is a Github repository that provides guidelines for writing clean and maintainable JavaScript code. It includes best practices and examples for naming conventions, functions, comments, formatting, and more.","archived":false,"fork":false,"pushed_at":"2023-06-03T12:01:51.000Z","size":82,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-13T10:30:54.103Z","etag":null,"topics":["best-practices","clean-code","docs","javascript","kazuma512","testing"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kazuma512.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2023-06-03T12:00:59.000Z","updated_at":"2024-04-16T09:26:44.000Z","dependencies_parsed_at":null,"dependency_job_id":"7e3d9608-4465-424e-81be-8d0ca872b259","html_url":"https://github.com/kazuma512/clean-code-javascript","commit_stats":null,"previous_names":["uchiha123456/clean-code-javascript","kazuma512/clean-code-javascript"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/kazuma512/clean-code-javascript","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kazuma512%2Fclean-code-javascript","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kazuma512%2Fclean-code-javascript/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kazuma512%2Fclean-code-javascript/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kazuma512%2Fclean-code-javascript/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kazuma512","download_url":"https://codeload.github.com/kazuma512/clean-code-javascript/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kazuma512%2Fclean-code-javascript/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261064457,"owners_count":23104725,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["best-practices","clean-code","docs","javascript","kazuma512","testing"],"created_at":"2024-11-06T04:15:40.546Z","updated_at":"2025-06-21T04:37:33.640Z","avatar_url":"https://github.com/kazuma512.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# clean-code-javascript\n\n## Table of Contents\n  1. [Introduction](#introduction)\n  2. [Variables](#variables)\n  3. [Functions](#functions)\n  4. [Objects and Data Structures](#objects-and-data-structures)\n  5. [Classes](#classes)\n  6. [Testing](#testing)\n  7. [Concurrency](#concurrency)\n  8. [Error Handling](#error-handling)\n  9. [Formatting](#formatting)\n  10. [Comments](#comments)\n\n## Introduction\n![Humorous image of software quality estimation as a count of how many expletives\nyou shout when reading code](http://www.osnews.com/images/comics/wtfm.jpg)\n\nSoftware engineering principles, from Robert C. Martin's book\n[*Clean Code*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882),\nadapted for JavaScript. This is not a style guide. It's a guide to producing\nreadable, reusable, and refactorable software in JavaScript.\n\nNot every principle herein has to be strictly followed, and even fewer will be\nuniversally agreed upon. These are guidelines and nothing more, but they are\nones codified over many years of collective experience by the authors of\n*Clean Code*.\n\nOur craft of software engineering is just a bit over 50 years old, and we are\nstill learning a lot. When software architecture is as old as architecture\nitself, maybe then we will have harder rules to follow. For now, let these\nguidelines serve as a touchstone by which to assess the quality of the\nJavaScript code that you and your team produce.\n\nOne more thing: knowing these won't immediately make you a better software\ndeveloper, and working with them for many years doesn't mean you won't make\nmistakes. Every piece of code starts as a first draft, like wet clay getting\nshaped into its final form. Finally, we chisel away the imperfections when\nwe review it with our peers. Don't beat yourself up for first drafts that need\nimprovement. Beat up the code instead!\n\n## **Variables**\n### Use meaningful and pronounceable variable names\n\n**Bad:**\n```javascript\nconst yyyymmdstr = moment().format('YYYY/MM/DD');\n```\n\n**Good**:\n```javascript\nconst yearMonthDay = moment().format('YYYY/MM/DD');\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Use the same vocabulary for the same type of variable\n\n**Bad:**\n```javascript\ngetUserInfo();\ngetClientData();\ngetCustomerRecord();\n```\n\n**Good**:\n```javascript\ngetUser();\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Use searchable names\nWe will read more code than we will ever write. It's important that the code we\ndo write is readable and searchable. By *not* naming variables that end up\nbeing meaningful for understanding our program, we hurt our readers.\nMake your names searchable.\n\n**Bad:**\n```javascript\n// What the heck is 525600 for?\nfor (let i = 0; i \u003c 525600; i++) {\n  runCronJob();\n}\n```\n\n**Good**:\n```javascript\n// Declare them as capitalized `const` globals.\nconst MINUTES_IN_A_YEAR = 525600;\nfor (let i = 0; i \u003c MINUTES_IN_A_YEAR; i++) {\n  runCronJob();\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Use explanatory variables\n**Bad:**\n```javascript\nconst cityStateRegex = /^(.+)[,\\\\s]+(.+?)\\s*(\\d{5})?$/;\nsaveCityState(cityStateRegex.match(cityStateRegex)[1], cityStateRegex.match(cityStateRegex)[2]);\n```\n\n**Good**:\n```javascript\nconst cityStateRegex = /^(.+)[,\\\\s]+(.+?)\\s*(\\d{5})?$/;\nconst match = cityStateRegex.match(cityStateRegex)\nconst city = match[1];\nconst state = match[2];\nsaveCityState(city, state);\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid Mental Mapping\nExplicit is better than implicit.\n\n**Bad:**\n```javascript\nconst locations = ['Austin', 'New York', 'San Francisco'];\nlocations.forEach((l) =\u003e {\n  doStuff();\n  doSomeOtherStuff();\n  // ...\n  // ...\n  // ...\n  // Wait, what is `l` for again?\n  dispatch(l);\n});\n```\n\n**Good**:\n```javascript\nconst locations = ['Austin', 'New York', 'San Francisco'];\nlocations.forEach((location) =\u003e {\n  doStuff();\n  doSomeOtherStuff();\n  // ...\n  // ...\n  // ...\n  dispatch(location);\n});\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Don't add unneeded context\nIf your class/object name tells you something, don't repeat that in your\nvariable name.\n\n**Bad:**\n```javascript\nconst Car = {\n  carMake: 'Honda',\n  carModel: 'Accord',\n  carColor: 'Blue'\n};\n\nfunction paintCar(car) {\n  car.carColor = 'Red';\n}\n```\n\n**Good**:\n```javascript\nconst Car = {\n  make: 'Honda',\n  model: 'Accord',\n  color: 'Blue'\n};\n\nfunction paintCar(car) {\n  car.color = 'Red';\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Short-circuiting is cleaner than conditionals\n\n**Bad:**\n```javascript\nfunction createMicrobrewery(name) {\n  let breweryName;\n  if (name) {\n    breweryName = name;\n  } else {\n    breweryName = 'Hipster Brew Co.';\n  }\n}\n```\n\n**Good**:\n```javascript\nfunction createMicrobrewery(name) {\n  const breweryName = name || 'Hipster Brew Co.'\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n## **Functions**\n### Function arguments (2 or fewer ideally)\nLimiting the amount of function parameters is incredibly important because it\nmakes testing your function easier. Having more than three leads to a\ncombinatorial explosion where you have to test tons of different cases with\neach separate argument.\n\nZero arguments is the ideal case. One or two arguments is ok, and three should\nbe avoided. Anything more than that should be consolidated. Usually, if you have\nmore than two arguments then your function is trying to do too much. In cases\nwhere it's not, most of the time a higher-level object will suffice as an\nargument.\n\nSince JavaScript allows us to make objects on the fly, without a lot of class\nboilerplate, you can use an object if you are finding yourself needing a\nlot of arguments.\n\n**Bad:**\n```javascript\nfunction createMenu(title, body, buttonText, cancellable) {\n  // ...\n}\n```\n\n**Good**:\n```javascript\nconst menuConfig = {\n  title: 'Foo',\n  body: 'Bar',\n  buttonText: 'Baz',\n  cancellable: true\n}\n\nfunction createMenu(menuConfig) {\n  // ...\n}\n\n```\n**[⬆ back to top](#table-of-contents)**\n\n\n### Functions should do one thing\nThis is by far the most important rule in software engineering. When functions\ndo more than one thing, they are harder to compose, test, and reason about.\nWhen you can isolate a function to just one action, they can be refactored\neasily and your code will read much cleaner. If you take nothing else away from\nthis guide other than this, you'll be ahead of many developers.\n\n**Bad:**\n```javascript\nfunction emailClients(clients) {\n  clients.forEach(client =\u003e {\n    const clientRecord = database.lookup(client);\n    if (clientRecord.isActive()) {\n      email(client);\n    }\n  });\n}\n```\n\n**Good**:\n```javascript\nfunction emailClients(clients) {\n  clients\n    .filter(isClientActive)\n    .forEach(email);\n}\n\nfunction isClientActive(client) {\n  const clientRecord = database.lookup(client);\n  return clientRecord.isActive();\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Function names should say what they do\n\n**Bad:**\n```javascript\nfunction dateAdd(date, month) {\n  // ...\n}\n\nconst date = new Date();\n\n// It's hard to to tell from the function name what is added\ndateAdd(date, 1);\n```\n\n**Good**:\n```javascript\nfunction dateAddMonth(date, month) {\n  // ...\n}\n\nconst date = new Date();\ndateAddMonth(date, 1);\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Functions should only be one level of abstraction\nWhen you have more than one level of abstraction your function is usually\ndoing too much. Splitting up functions leads to reusability and easier\ntesting.\n\n**Bad:**\n```javascript\nfunction parseBetterJSAlternative(code) {\n  const REGEXES = [\n    // ...\n  ];\n\n  const statements = code.split(' ');\n  const tokens = [];\n  REGEXES.forEach((REGEX) =\u003e {\n    statements.forEach((statement) =\u003e {\n      // ...\n    })\n  });\n\n  const ast = [];\n  tokens.forEach((token) =\u003e {\n    // lex...\n  });\n\n  ast.forEach((node) =\u003e {\n    // parse...\n  })\n}\n```\n\n**Good**:\n```javascript\nfunction tokenize(code) {\n  const REGEXES = [\n    // ...\n  ];\n\n  const statements = code.split(' ');\n  const tokens = [];\n  REGEXES.forEach((REGEX) =\u003e {\n    statements.forEach((statement) =\u003e {\n      tokens.push( /* ... */ );\n    })\n  });\n\n  return tokens;\n}\n\nfunction lexer(tokens) {\n  const ast = [];\n  tokens.forEach((token) =\u003e {\n    ast.push( /* ... */ );\n  });\n\n  return ast;\n}\n\nfunction parseBetterJSAlternative(code) {\n  const tokens = tokenize(code);\n  const ast = lexer(tokens);\n  ast.forEach((node) =\u003e {\n    // parse...\n  })\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Remove duplicate code\nNever ever, ever, under any circumstance, have duplicate code. There's no reason\nfor it and it's quite possibly the worst sin you can commit as a professional\ndeveloper. Duplicate code means there's more than one place to alter something\nif you need to change some logic. JavaScript is untyped, so it makes having\ngeneric functions quite easy. Take advantage of that! Tools like\n[jsinpect](https://github.com/danielstjules/jsinspect) can help you find duplicate\ncode eligible for refactoring.\n\n**Bad:**\n```javascript\nfunction showDeveloperList(developers) {\n  developers.forEach(developer =\u003e {\n    const expectedSalary = developer.calculateExpectedSalary();\n    const experience = developer.getExperience();\n    const githubLink = developer.getGithubLink();\n    const data = {\n      expectedSalary: expectedSalary,\n      experience: experience,\n      githubLink: githubLink\n    };\n\n    render(data);\n  });\n}\n\nfunction showManagerList(managers) {\n  managers.forEach(manager =\u003e {\n    const expectedSalary = manager.calculateExpectedSalary();\n    const experience = manager.getExperience();\n    const portfolio = manager.getMBAProjects();\n    const data = {\n      expectedSalary: expectedSalary,\n      experience: experience,\n      portfolio: portfolio\n    };\n\n    render(data);\n  });\n}\n```\n\n**Good**:\n```javascript\nfunction showList(employees) {\n  employees.forEach(employee =\u003e {\n    const expectedSalary = employee.calculateExpectedSalary();\n    const experience = employee.getExperience();\n\n    let portfolio = employee.getGithubLink();\n\n    if (employee.type === 'manager') {\n      portfolio = employee.getMBAProjects();\n    }\n\n    const data = {\n      expectedSalary: expectedSalary,\n      experience: experience,\n      portfolio: portfolio\n    };\n\n    render(data);\n  });\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Use default arguments instead of short circuiting\n**Bad:**\n```javascript\nfunction writeForumComment(subject, body) {\n  subject = subject || 'No Subject';\n  body = body || 'No text';\n}\n\n```\n\n**Good**:\n```javascript\nfunction writeForumComment(subject = 'No subject', body = 'No text') {\n  // ...\n}\n\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Set default objects with Object.assign\n\n**Bad:**\n```javascript\nconst menuConfig = {\n  title: null,\n  body: 'Bar',\n  buttonText: null,\n  cancellable: true\n}\n\nfunction createMenu(config) {\n  config.title = config.title || 'Foo'\n  config.body = config.body || 'Bar'\n  config.buttonText = config.buttonText || 'Baz'\n  config.cancellable = config.cancellable === undefined ? config.cancellable : true;\n\n}\n\ncreateMenu(menuConfig);\n```\n\n**Good**:\n```javascript\nconst menuConfig = {\n  title: 'Order',\n  // User did not include 'body' key\n  buttonText: 'Send',\n  cancellable: true\n}\n\nfunction createMenu(config) {\n  config = Object.assign({\n    title: 'Foo',\n    body: 'Bar',\n    buttonText: 'Baz',\n    cancellable: true\n  }, config);\n\n  // config now equals: {title: \"Order\", body: \"Bar\", buttonText: \"Send\", cancellable: true}\n  // ...\n}\n\ncreateMenu(menuConfig);\n```\n**[⬆ back to top](#table-of-contents)**\n\n\n### Don't use flags as function parameters\nFlags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean.\n\n**Bad:**\n```javascript\nfunction createFile(name, temp) {\n  if (temp) {\n    fs.create('./temp/' + name);\n  } else {\n    fs.create(name);\n  }\n}\n```\n\n**Good**:\n```javascript\nfunction createFile(name) {\n  fs.create(name);\n}\n\nfunction createTempFile(name) {\n  createFile('./temp/' + name);\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid Side Effects\nA function produces a side effect if it does anything other than take a value in\nand return another value or values. A side effect could be writing to a file,\nmodifying some global variable, or accidentally wiring all your money to a\nstranger.\n\nNow, you do need to have side effects in a program on occasion. Like the previous\nexample, you might need to write to a file. What you want to do is to\ncentralize where you are doing this. Don't have several functions and classes\nthat write to a particular file. Have one service that does it. One and only one.\n\nThe main point is to avoid common pitfalls like sharing state between objects\nwithout any structure, using mutable data types that can be written to by anything,\nand not centralizing where your side effects occur. If you can do this, you will\nbe happier than the vast majority of other programmers.\n\n**Bad:**\n```javascript\n// Global variable referenced by following function.\n// If we had another function that used this name, now it'd be an array and it could break it.\nlet name = 'Ryan McDermott';\n\nfunction splitIntoFirstAndLastName() {\n  name = name.split(' ');\n}\n\nsplitIntoFirstAndLastName();\n\nconsole.log(name); // ['Ryan', 'McDermott'];\n```\n\n**Good**:\n```javascript\nfunction splitIntoFirstAndLastName(name) {\n  return name.split(' ');\n}\n\nconst name = 'Ryan McDermott'\nconst newName = splitIntoFirstAndLastName(name);\n\nconsole.log(name); // 'Ryan McDermott';\nconsole.log(newName); // ['Ryan', 'McDermott'];\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Don't write to global functions\nPolluting globals is a bad practice in JavaScript because you could clash with another\nlibrary and the user of your API would be none-the-wiser until they get an\nexception in production. Let's think about an example: what if you wanted to\nextend JavaScript's native Array method to have a `diff` method that could\nshow the difference between two arrays? You could write your new function\nto the `Array.prototype`, but it could clash with another library that tried\nto do the same thing. What if that other library was just using `diff` to find\nthe difference between the first and last elements of an array? This is why it\nwould be much better to just use ES2015/ES6 classes and simply extend the `Array` global.\n\n**Bad:**\n```javascript\nArray.prototype.diff = function(comparisonArray) {\n  const values = [];\n  const hash = {};\n\n  for (const i of comparisonArray) {\n    hash[i] = true;\n  }\n\n  for (const i of this) {\n    if (!hash[i]) {\n      values.push(i);\n    }\n  }\n\n  return values;\n}\n```\n\n**Good:**\n```javascript\nclass SuperArray extends Array {\n  constructor(...args) {\n    super(...args);\n  }\n\n  diff(comparisonArray) {\n    const values = [];\n    const hash = {};\n\n    for (const i of comparisonArray) {\n      hash[i] = true;\n    }\n\n    for (const i of this) {\n      if (!hash[i]) {\n        values.push(i);\n      }\n    }\n\n    return values;\n  }\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Favor functional programming over imperative programming\nJavaScript isn't a functional language in the way that Haskell is, but it has\na functional flavor to it. Functional languages are cleaner and easier to test.\nFavor this style of programming when you can.\n\n**Bad:**\n```javascript\nconst programmerOutput = [\n  {\n    name: 'Uncle Bobby',\n    linesOfCode: 500\n  }, {\n    name: 'Suzie Q',\n    linesOfCode: 1500\n  }, {\n    name: 'Jimmy Gosling',\n    linesOfCode: 150\n  }, {\n    name: 'Gracie Hopper',\n    linesOfCode: 1000\n  }\n];\n\nlet totalOutput = 0;\n\nfor (let i = 0; i \u003c programmerOutput.length; i++) {\n  totalOutput += programmerOutput[i].linesOfCode;\n}\n```\n\n**Good**:\n```javascript\nconst programmerOutput = [\n  {\n    name: 'Uncle Bobby',\n    linesOfCode: 500\n  }, {\n    name: 'Suzie Q',\n    linesOfCode: 1500\n  }, {\n    name: 'Jimmy Gosling',\n    linesOfCode: 150\n  }, {\n    name: 'Gracie Hopper',\n    linesOfCode: 1000\n  }\n];\n\nconst totalOutput = programmerOutput\n  .map((programmer) =\u003e programmer.linesOfCode)\n  .reduce((acc, linesOfCode) =\u003e acc + linesOfCode, 0);\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Encapsulate conditionals\n\n**Bad:**\n```javascript\nif (fsm.state === 'fetching' \u0026\u0026 isEmpty(listNode)) {\n  // ...\n}\n```\n\n**Good**:\n```javascript\nfunction shouldShowSpinner(fsm, listNode) {\n  return fsm.state === 'fetching' \u0026\u0026 isEmpty(listNode);\n}\n\nif (shouldShowSpinner(fsmInstance, listNodeInstance)) {\n  // ...\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid negative conditionals\n\n**Bad:**\n```javascript\nfunction isDOMNodeNotPresent(node) {\n  // ...\n}\n\nif (!isDOMNodeNotPresent(node)) {\n  // ...\n}\n```\n\n**Good**:\n```javascript\nfunction isDOMNodePresent(node) {\n  // ...\n}\n\nif (isDOMNodePresent(node)) {\n  // ...\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid conditionals\nThis seems like an impossible task. Upon first hearing this, most people say,\n\"how am I supposed to do anything without an `if` statement?\" The answer is that\nyou can use polymorphism to achieve the same task in many cases. The second\nquestion is usually, \"well that's great but why would I want to do that?\" The\nanswer is a previous clean code concept we learned: a function should only do\none thing. When you have classes and functions that have `if` statements, you\nare telling your user that your function does more than one thing. Remember,\njust do one thing.\n\n**Bad:**\n```javascript\nclass Airplane {\n  // ...\n  getCruisingAltitude() {\n    switch (this.type) {\n      case '777':\n        return getMaxAltitude() - getPassengerCount();\n      case 'Air Force One':\n        return getMaxAltitude();\n      case 'Cessna':\n        return getMaxAltitude() - getFuelExpenditure();\n    }\n  }\n}\n```\n\n**Good**:\n```javascript\nclass Airplane {\n  // ...\n}\n\nclass Boeing777 extends Airplane {\n  // ...\n  getCruisingAltitude() {\n    return getMaxAltitude() - getPassengerCount();\n  }\n}\n\nclass AirForceOne extends Airplane {\n  // ...\n  getCruisingAltitude() {\n    return getMaxAltitude();\n  }\n}\n\nclass Cessna extends Airplane {\n  // ...\n  getCruisingAltitude() {\n    return getMaxAltitude() - getFuelExpenditure();\n  }\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid type-checking (part 1)\nJavaScript is untyped, which means your functions can take any type of argument.\nSometimes you are bitten by this freedom and it becomes tempting to do\ntype-checking in your functions. There are many ways to avoid having to do this.\nThe first thing to consider is consistent APIs.\n\n**Bad:**\n```javascript\nfunction travelToTexas(vehicle) {\n  if (vehicle instanceof Bicycle) {\n    vehicle.peddle(this.currentLocation, new Location('texas'));\n  } else if (vehicle instanceof Car) {\n    vehicle.drive(this.currentLocation, new Location('texas'));\n  }\n}\n```\n\n**Good**:\n```javascript\nfunction travelToTexas(vehicle) {\n  vehicle.move(this.currentLocation, new Location('texas'));\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid type-checking (part 2)\nIf you are working with basic primitive values like strings, integers, and arrays,\nand you can't use polymorphism but you still feel the need to type-check,\nyou should consider using TypeScript. It is an excellent alternative to normal\nJavaScript, as it provides you with static typing on top of standard JavaScript\nsyntax. The problem with manually type-checking normal JavaScript is that\ndoing it well requires so much extra verbiage that the faux \"type-safety\" you get\ndoesn't make up for the lost readability. Keep your JavaScript clean, write\ngood tests, and have good code reviews. Otherwise, do all of that but with\nTypeScript (which, like I said, is a great alternative!).\n\n**Bad:**\n```javascript\nfunction combine(val1, val2) {\n  if (typeof val1 == \"number\" \u0026\u0026 typeof val2 == \"number\" ||\n      typeof val1 == \"string\" \u0026\u0026 typeof val2 == \"string\") {\n    return val1 + val2;\n  } else {\n    throw new Error('Must be of type String or Number');\n  }\n}\n```\n\n**Good**:\n```javascript\nfunction combine(val1, val2) {\n  return val1 + val2;\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Don't over-optimize\nModern browsers do a lot of optimization under-the-hood at runtime. A lot of\ntimes, if you are optimizing then you are just wasting your time. [There are good\nresources](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers)\nfor seeing where optimization is lacking. Target those in the meantime, until\nthey are fixed if they can be.\n\n**Bad:**\n```javascript\n\n// On old browsers, each iteration with uncached `list.length` would be costly\n// because of `list.length` recomputation. In modern browsers, this is optimized.\nfor (let i = 0, len = list.length; i \u003c len; i++) {\n  // ...\n}\n```\n\n**Good**:\n```javascript\nfor (let i = 0; i \u003c list.length; i++) {\n  // ...\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Remove dead code\nDead code is just as bad as duplicate code. There's no reason to keep it in\nyour codebase. If it's not being called, get rid of it! It will still be safe\nin your version history if you still need it.\n\n**Bad:**\n```javascript\nfunction oldRequestModule(url) {\n  // ...\n}\n\nfunction newRequestModule(url) {\n  // ...\n}\n\nconst req = newRequestModule;\ninventoryTracker('apples', req, 'www.inventory-awesome.io');\n\n```\n\n**Good**:\n```javascript\nfunction newRequestModule(url) {\n  // ...\n}\n\nconst req = newRequestModule;\ninventoryTracker('apples', req, 'www.inventory-awesome.io');\n```\n**[⬆ back to top](#table-of-contents)**\n\n## **Objects and Data Structures**\n### Use getters and setters\nJavaScript doesn't have interfaces or types so it is very hard to enforce this\npattern, because we don't have keywords like `public` and `private`. As it is,\nusing getters and setters to access data on objects is far better than simply\nlooking for a property on an object. \"Why?\" you might ask. Well, here's an\nunorganized list of reasons why:\n\n1. When you want to do more beyond getting an object property, you don't have\nto look up and change every accessor in your codebase.\n2. Makes adding validation simple when doing a `set`.\n3. Encapsulates the internal representation.\n4. Easy to add logging and error handling when getting and setting.\n5. Inheriting this class, you can override default functionality.\n6. You can lazy load your object's properties, let's say getting it from a\nserver.\n\n\n**Bad:**\n```javascript\nclass BankAccount {\n  constructor() {\n    this.balance = 1000;\n  }\n}\n\nconst bankAccount = new BankAccount();\n\n// Buy shoes...\nbankAccount.balance = bankAccount.balance - 100;\n```\n\n**Good**:\n```javascript\nclass BankAccount {\n  constructor() {\n    this.balance = 1000;\n  }\n\n  // It doesn't have to be prefixed with `get` or `set` to be a getter/setter\n  withdraw(amount) {\n    if (verifyAmountCanBeDeducted(amount)) {\n      this.balance -= amount;\n    }\n  }\n}\n\nconst bankAccount = new BankAccount();\n\n// Buy shoes...\nbankAccount.withdraw(100);\n```\n**[⬆ back to top](#table-of-contents)**\n\n\n### Make objects have private members\nThis can be accomplished through closures (for ES5 and below).\n\n**Bad:**\n```javascript\n\nconst Employee = function(name) {\n  this.name = name;\n}\n\nEmployee.prototype.getName = function() {\n  return this.name;\n}\n\nconst employee = new Employee('John Doe');\nconsole.log('Employee name: ' + employee.getName()); // Employee name: John Doe\ndelete employee.name;\nconsole.log('Employee name: ' + employee.getName()); // Employee name: undefined\n```\n\n**Good**:\n```javascript\nconst Employee = (function() {\n  function Employee(name) {\n    this.getName = function() {\n      return name;\n    };\n  }\n\n  return Employee;\n}());\n\nconst employee = new Employee('John Doe');\nconsole.log('Employee name: ' + employee.getName()); // Employee name: John Doe\ndelete employee.name;\nconsole.log('Employee name: ' + employee.getName()); // Employee name: John Doe\n```\n**[⬆ back to top](#table-of-contents)**\n\n\n## **Classes**\n### Single Responsibility Principle (SRP)\nAs stated in Clean Code, \"There should never be more than one reason for a class\nto change\". It's tempting to jam-pack a class with a lot of functionality, like\nwhen you can only take one suitcase on your flight. The issue with this is\nthat your class won't be conceptually cohesive and it will give it many reasons\nto change. Minimizing the amount of times you need to change a class is important.\nIt's important because if too much functionality is in one class and you modify a piece of it,\nit can be difficult to understand how that will affect other dependent modules in\nyour codebase.\n\n**Bad:**\n```javascript\nclass UserSettings {\n  constructor(user) {\n    this.user = user;\n  }\n\n  changeSettings(settings) {\n    if (this.verifyCredentials(user)) {\n      // ...\n    }\n  }\n\n  verifyCredentials(user) {\n    // ...\n  }\n}\n```\n\n**Good**:\n```javascript\nclass UserAuth {\n  constructor(user) {\n    this.user = user;\n  }\n\n  verifyCredentials() {\n    // ...\n  }\n}\n\n\nclass UserSettings {\n  constructor(user) {\n    this.user = user;\n    this.auth = new UserAuth(user)\n  }\n\n  changeSettings(settings) {\n    if (this.auth.verifyCredentials()) {\n      // ...\n    }\n  }\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Open/Closed Principle (OCP)\nAs stated by Bertrand Meyer, \"software entities (classes, modules, functions,\netc.) should be open for extension, but closed for modification.\" What does that\nmean though? This principle basically states that you should allow users to\nextend the functionality of your module without having to open up the `.js`\nsource code file and manually manipulate it.\n\n**Bad:**\n```javascript\nclass AjaxRequester {\n  constructor() {\n    // What if we wanted another HTTP Method, like DELETE? We would have to\n    // open this file up and modify this and put it in manually.\n    this.HTTP_METHODS = ['POST', 'PUT', 'GET'];\n  }\n\n  get(url) {\n    // ...\n  }\n\n}\n```\n\n**Good**:\n```javascript\nclass AjaxRequester {\n  constructor() {\n    this.HTTP_METHODS = ['POST', 'PUT', 'GET'];\n  }\n\n  get(url) {\n    // ...\n  }\n\n  addHTTPMethod(method) {\n    this.HTTP_METHODS.push(method);\n  }\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n\n### Liskov Substitution Principle (LSP)\nThis is a scary term for a very simple concept. It's formally defined as \"If S\nis a subtype of T, then objects of type T may be replaced with objects of type S\n(i.e., objects of type S may substitute objects of type T) without altering any\nof the desirable properties of that program (correctness, task performed,\netc.).\" That's an even scarier definition.\n\nThe best explanation for this is if you have a parent class and a child class,\nthen the base class and child class can be used interchangeably without getting\nincorrect results. This might still be confusing, so let's take a look at the\nclassic Square-Rectangle example. Mathematically, a square is a rectangle, but\nif you model it using the \"is-a\" relationship via inheritance, you quickly\nget into trouble.\n\n**Bad:**\n```javascript\nclass Rectangle {\n  constructor() {\n    this.width = 0;\n    this.height = 0;\n  }\n\n  setColor(color) {\n    // ...\n  }\n\n  render(area) {\n    // ...\n  }\n\n  setWidth(width) {\n    this.width = width;\n  }\n\n  setHeight(height) {\n    this.height = height;\n  }\n\n  getArea() {\n    return this.width * this.height;\n  }\n}\n\nclass Square extends Rectangle {\n  constructor() {\n    super();\n  }\n\n  setWidth(width) {\n    this.width = width;\n    this.height = width;\n  }\n\n  setHeight(height) {\n    this.width = height;\n    this.height = height;\n  }\n}\n\nfunction renderLargeRectangles(rectangles) {\n  rectangles.forEach((rectangle) =\u003e {\n    rectangle.setWidth(4);\n    rectangle.setHeight(5);\n    const area = rectangle.getArea(); // BAD: Will return 25 for Square. Should be 20.\n    rectangle.render(area);\n  })\n}\n\nconst rectangles = [new Rectangle(), new Rectangle(), new Square()];\nrenderLargeRectangles(rectangles);\n```\n\n**Good**:\n```javascript\nclass Shape {\n  constructor() {}\n\n  setColor(color) {\n    // ...\n  }\n\n  render(area) {\n    // ...\n  }\n}\n\nclass Rectangle extends Shape {\n  constructor() {\n    super();\n    this.width = 0;\n    this.height = 0;\n  }\n\n  setWidth(width) {\n    this.width = width;\n  }\n\n  setHeight(height) {\n    this.height = height;\n  }\n\n  getArea() {\n    return this.width * this.height;\n  }\n}\n\nclass Square extends Shape {\n  constructor() {\n    super();\n    this.length = 0;\n  }\n\n  setLength(length) {\n    this.length = length;\n  }\n\n  getArea() {\n    return this.length * this.length;\n  }\n}\n\nfunction renderLargeShapes(shapes) {\n  shapes.forEach((shape) =\u003e {\n    switch (shape.constructor.name) {\n      case 'Square':\n        shape.setLength(5);\n      case 'Rectangle':\n        shape.setWidth(4);\n        shape.setHeight(5);\n    }\n\n    const area = shape.getArea();\n    shape.render(area);\n  })\n}\n\nconst shapes = [new Rectangle(), new Rectangle(), new Square()];\nrenderLargeShapes(shapes);\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Interface Segregation Principle (ISP)\nJavaScript doesn't have interfaces so this principle doesn't apply as strictly\nas others. However, it's important and relevant even with JavaScript's lack of\ntype system.\n\nISP states that \"Clients should not be forced to depend upon interfaces that\nthey do not use.\" Interfaces are implicit contracts in JavaScript because of\nduck typing.\n\nA good example to look at that demonstrates this principle in JavaScript is for\nclasses that require large settings objects. Not requiring clients to setup\nhuge amounts of options is beneficial, because most of the time they won't need\nall of the settings. Making them optional helps prevent having a \"fat interface\".\n\n**Bad:**\n```javascript\nclass DOMTraverser {\n  constructor(settings) {\n    this.settings = settings;\n    this.setup();\n  }\n\n  setup() {\n    this.rootNode = this.settings.rootNode;\n    this.animationModule.setup();\n  }\n\n  traverse() {\n    // ...\n  }\n}\n\nconst $ = new DOMTraverser({\n  rootNode: document.getElementsByTagName('body'),\n  animationModule: function() {} // Most of the time, we won't need to animate when traversing.\n  // ...\n});\n\n```\n\n**Good**:\n```javascript\nclass DOMTraverser {\n  constructor(settings) {\n    this.settings = settings;\n    this.options = settings.options;\n    this.setup();\n  }\n\n  setup() {\n    this.rootNode = this.settings.rootNode;\n    this.setupOptions();\n  }\n\n  setupOptions() {\n    if (this.options.animationModule) {\n      // ...\n    }\n  }\n\n  traverse() {\n    // ...\n  }\n}\n\nconst $ = new DOMTraverser({\n  rootNode: document.getElementsByTagName('body'),\n  options: {\n    animationModule: function() {}\n  }\n});\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Dependency Inversion Principle (DIP)\nThis principle states two essential things:\n1. High-level modules should not depend on low-level modules. Both should\ndepend on abstractions.\n2. Abstractions should not depend upon details. Details should depend on\nabstractions.\n\nThis can be hard to understand at first, but if you've worked with Angular.js,\nyou've seen an implementation of this principle in the form of Dependency\nInjection (DI). While they are not identical concepts, DIP keeps high-level\nmodules from knowing the details of its low-level modules and setting them up.\nIt can accomplish this through DI. A huge benefit of this is that it reduces\nthe coupling between modules. Coupling is a very bad development pattern because\nit makes your code hard to refactor.\n\nAs stated previously, JavaScript doesn't have interfaces so the abstractions\nthat are depended upon are implicit contracts. That is to say, the methods\nand properties that an object/class exposes to another object/class. In the\nexample below, the implicit contract is that any Request module for an\n`InventoryTracker` will have a `requestItems` method.\n\n**Bad:**\n```javascript\nclass InventoryTracker {\n  constructor(items) {\n    this.items = items;\n\n    // BAD: We have created a dependency on a specific request implementation.\n    // We should just have requestItems depend on a request method: `request`\n    this.requester = new InventoryRequester();\n  }\n\n  requestItems() {\n    this.items.forEach((item) =\u003e {\n      this.requester.requestItem(item);\n    });\n  }\n}\n\nclass InventoryRequester {\n  constructor() {\n    this.REQ_METHODS = ['HTTP'];\n  }\n\n  requestItem(item) {\n    // ...\n  }\n}\n\nconst inventoryTracker = new InventoryTracker(['apples', 'bananas']);\ninventoryTracker.requestItems();\n```\n\n**Good**:\n```javascript\nclass InventoryTracker {\n  constructor(items, requester) {\n    this.items = items;\n    this.requester = requester;\n  }\n\n  requestItems() {\n    this.items.forEach((item) =\u003e {\n      this.requester.requestItem(item);\n    });\n  }\n}\n\nclass InventoryRequesterV1 {\n  constructor() {\n    this.REQ_METHODS = ['HTTP'];\n  }\n\n  requestItem(item) {\n    // ...\n  }\n}\n\nclass InventoryRequesterV2 {\n  constructor() {\n    this.REQ_METHODS = ['WS'];\n  }\n\n  requestItem(item) {\n    // ...\n  }\n}\n\n// By constructing our dependencies externally and injecting them, we can easily\n// substitute our request module for a fancy new one that uses WebSockets.\nconst inventoryTracker = new InventoryTracker(['apples', 'bananas'], new InventoryRequesterV2());\ninventoryTracker.requestItems();\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Prefer ES2015/ES6 classes over ES5 plain functions\nIt's very difficult to get readable class inheritance, construction, and method\ndefinitions for classical ES5 classes. If you need inheritance (and be aware\nthat you might not), then prefer classes. However, prefer small functions over\nclasses until you find yourself needing larger and more complex objects.\n\n**Bad:**\n```javascript\nconst Animal = function(age) {\n    if (!(this instanceof Animal)) {\n        throw new Error(\"Instantiate Animal with `new`\");\n    }\n\n    this.age = age;\n};\n\nAnimal.prototype.move = function() {};\n\nconst Mammal = function(age, furColor) {\n    if (!(this instanceof Mammal)) {\n        throw new Error(\"Instantiate Mammal with `new`\");\n    }\n\n    Animal.call(this, age);\n    this.furColor = furColor;\n};\n\nMammal.prototype = Object.create(Animal.prototype);\nMammal.prototype.constructor = Mammal;\nMammal.prototype.liveBirth = function() {};\n\nconst Human = function(age, furColor, languageSpoken) {\n    if (!(this instanceof Human)) {\n        throw new Error(\"Instantiate Human with `new`\");\n    }\n\n    Mammal.call(this, age, furColor);\n    this.languageSpoken = languageSpoken;\n};\n\nHuman.prototype = Object.create(Mammal.prototype);\nHuman.prototype.constructor = Human;\nHuman.prototype.speak = function() {};\n```\n\n**Good:**\n```javascript\nclass Animal {\n    constructor(age) {\n        this.age = age;\n    }\n\n    move() {}\n}\n\nclass Mammal extends Animal {\n    constructor(age, furColor) {\n        super(age);\n        this.furColor = furColor;\n    }\n\n    liveBirth() {}\n}\n\nclass Human extends Mammal {\n    constructor(age, furColor, languageSpoken) {\n        super(age, furColor);\n        this.languageSpoken = languageSpoken;\n    }\n\n    speak() {}\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n\n### Use method chaining\nAgainst the advice of Clean Code, this is one place where we will have to differ.\nIt has been argued that method chaining is unclean and violates the [Law of Demeter](https://en.wikipedia.org/wiki/Law_of_Demeter).\nMaybe it's true, but this pattern is very useful in JavaScript and you see it in\nmany libraries such as jQuery and Lodash. It allows your code to be expressive,\nand less verbose. For that reason, I say, use method chaining and take a look at\nhow clean your code will be. In your class functions, simply return `this` at\nthe end of every function, and you can chain further class methods onto it.\n\n**Bad:**\n```javascript\nclass Car {\n  constructor() {\n    this.make = 'Honda';\n    this.model = 'Accord';\n    this.color = 'white';\n  }\n\n  setMake(make) {\n    this.make = make;\n  }\n\n  setModel(model) {\n    this.model = model;\n  }\n\n  setColor(color) {\n    this.color = color;\n  }\n\n  save() {\n    console.log(this.make, this.model, this.color);\n  }\n}\n\nconst car = new Car();\ncar.setColor('pink');\ncar.setMake('Ford');\ncar.setModel('F-150')\ncar.save();\n```\n\n**Good**:\n```javascript\nclass Car {\n  constructor() {\n    this.make = 'Honda';\n    this.model = 'Accord';\n    this.color = 'white';\n  }\n\n  setMake(make) {\n    this.make = make;\n    // NOTE: Returning this for chaining\n    return this;\n  }\n\n  setModel(model) {\n    this.model = model;\n    // NOTE: Returning this for chaining\n    return this;\n  }\n\n  setColor(color) {\n    this.color = color;\n    // NOTE: Returning this for chaining\n    return this;\n  }\n\n  save() {\n    console.log(this.make, this.model, this.color);\n    // NOTE: Returning this for chaining\n    return this;\n  }\n}\n\nconst car = new Car()\n  .setColor('pink')\n  .setMake('Ford')\n  .setModel('F-150')\n  .save();\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Prefer composition over inheritance\nAs stated famously in [*Design Patterns*](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four,\nyou should prefer composition over inheritance where you can. There are lots of\ngood reasons to use inheritance and lots of good reasons to use composition.\nThe main point for this maxim is that if your mind instinctively goes for\ninheritance, try to think if composition could model your problem better. In some\ncases it can.\n\nYou might be wondering then, \"when should I use inheritance?\" It\ndepends on your problem at hand, but this is a decent list of when inheritance\nmakes more sense than composition:\n\n1. Your inheritance represents an \"is-a\" relationship and not a \"has-a\"\nrelationship (Animal-\u003eHuman vs. User-\u003eUserDetails).\n2. You can reuse code from the base classes (Humans can move like all animals).\n3. You want to make global changes to derived classes by changing a base class.\n(Change the caloric expenditure of all animals when they move).\n\n**Bad:**\n```javascript\nclass Employee {\n  constructor(name, email) {\n    this.name = name;\n    this.email = email;\n  }\n\n  // ...\n}\n\n// Bad because Employees \"have\" tax data. EmployeeTaxData is not a type of Employee\nclass EmployeeTaxData extends Employee {\n  constructor(ssn, salary) {\n    super();\n    this.ssn = ssn;\n    this.salary = salary;\n  }\n\n  // ...\n}\n```\n\n**Good**:\n```javascript\nclass Employee {\n  constructor(name, email) {\n    this.name = name;\n    this.email = email;\n\n  }\n\n  setTaxData(ssn, salary) {\n    this.taxData = new EmployeeTaxData(ssn, salary);\n  }\n  // ...\n}\n\nclass EmployeeTaxData {\n  constructor(ssn, salary) {\n    this.ssn = ssn;\n    this.salary = salary;\n  }\n\n  // ...\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n## **Testing**\nTesting is more important than shipping. If you have have no tests or an\ninadequate amount, then every time you ship code you won't be sure that you\ndidn't break anything. Deciding on what constitutes an adequate amount is up\nto your team, but having 100% coverage (all statements and branches) is how\nyou achieve very high confidence and developer peace of mind. This means that\nin addition to having a great testing framework, you also need to use a\n[good coverage tool](http://gotwarlost.github.io/istanbul/).\n\nThere's no excuse to not write tests. There's [plenty of good JS test frameworks]\n(http://jstherightway.org/#testing-tools), so find one that your team prefers.\nWhen you find one that works for your team, then aim to always write tests\nfor every new feature/module you introduce. If your preferred method is\nTest Driven Development (TDD), that is great, but the main point is to just\nmake sure you are reaching your coverage goals before launching any feature,\nor refactoring an existing one.\n\n### Single concept per test\n\n**Bad:**\n```javascript\nconst assert = require('assert');\n\ndescribe('MakeMomentJSGreatAgain', function() {\n  it('handles date boundaries', function() {\n    let date;\n\n    date = new MakeMomentJSGreatAgain('1/1/2015');\n    date.addDays(30);\n    date.shouldEqual('1/31/2015');\n\n    date = new MakeMomentJSGreatAgain('2/1/2016');\n    date.addDays(28);\n    assert.equal('02/29/2016', date);\n\n    date = new MakeMomentJSGreatAgain('2/1/2015');\n    date.addDays(28);\n    assert.equal('03/01/2015', date);\n  });\n});\n```\n\n**Good**:\n```javascript\nconst assert = require('assert');\n\ndescribe('MakeMomentJSGreatAgain', function() {\n  it('handles 30-day months', function() {\n    const date = new MakeMomentJSGreatAgain('1/1/2015');\n    date.addDays(30);\n    date.shouldEqual('1/31/2015');\n  });\n\n  it('handles leap year', function() {\n    const date = new MakeMomentJSGreatAgain('2/1/2016');\n    date.addDays(28);\n    assert.equal('02/29/2016', date);\n  });\n\n  it('handles non-leap year', function() {\n    const date = new MakeMomentJSGreatAgain('2/1/2015');\n    date.addDays(28);\n    assert.equal('03/01/2015', date);\n  });\n});\n```\n**[⬆ back to top](#table-of-contents)**\n\n## **Concurrency**\n### Use Promises, not callbacks\nCallbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6,\nPromises are a built-in global type. Use them!\n\n**Bad:**\n```javascript\nrequire('request').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', function(err, response) {\n  if (err) {\n    console.error(err);\n  }\n  else {\n    require('fs').writeFile('article.html', response.body, function(err) {\n      if (err) {\n        console.error(err);\n      } else {\n        console.log('File written');\n      }\n    })\n  }\n})\n\n```\n\n**Good**:\n```javascript\nrequire('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')\n  .then(function(response) {\n    return require('fs-promise').writeFile('article.html', response);\n  })\n  .then(function() {\n    console.log('File written');\n  })\n  .catch(function(err) {\n    console.error(err);\n  })\n\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Async/Await are even cleaner than Promises\nPromises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await\nwhich offer an even cleaner solution. All you need is a function that is prefixed\nin an `async` keyword, and then you can write your logic imperatively without\na `then` chain of functions. Use this if you can take advantage of ES2017/ES8 features\ntoday!\n\n**Bad:**\n```javascript\nrequire('request-promise').get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')\n  .then(function(response) {\n    return require('fs-promise').writeFile('article.html', response);\n  })\n  .then(function() {\n    console.log('File written');\n  })\n  .catch(function(err) {\n    console.error(err);\n  })\n\n```\n\n**Good**:\n```javascript\nasync function getCleanCodeArticle() {\n  try {\n    const request = await require('request-promise')\n    const response = await request.get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');\n    const fileHandle = await require('fs-promise');\n\n    await fileHandle.writeFile('article.html', response);\n    console.log('File written');\n  } catch(err) {\n    console.log(err);\n  }\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n\n## **Error Handling**\nThrown errors are a good thing! They mean the runtime has successfully\nidentified when something in your program has gone wrong and it's letting\nyou know by stopping function execution on the current stack, killing the\nprocess (in Node), and notifying you in the console with a stack trace.\n\n### Don't ignore caught errors\nDoing nothing with a caught error doesn't give you the ability to ever fix\nor react to said error. Logging the error to the console (`console.log`)\nisn't much better as often times it can get lost in a sea of things printed\nto the console. If you wrap any bit of code in a `try/catch` it means you\nthink an error may occur there and therefore you should have a plan,\nor create a code path, for when it occurs.\n\n**Bad:**\n```javascript\ntry {\n  functionThatMightThrow();\n} catch (error) {\n  console.log(error);\n}\n```\n\n**Good:**\n```javascript\ntry {\n  functionThatMightThrow();\n} catch (error) {\n  // One option (more noisy than console.log):\n  console.error(error);\n  // Another option:\n  notifyUserOfError(error);\n  // Another option:\n  reportErrorToService(error);\n  // OR do all three!\n}\n```\n\n### Don't ignore rejected promises\nFor the same reason you shouldn't ignore caught errors\nfrom `try/catch`.\n\n**Bad:**\n```javascript\ngetdata()\n.then(data =\u003e {\n  functionThatMightThrow(data);\n})\n.catch(error =\u003e {\n  console.log(error);\n});\n```\n\n**Good:**\n```javascript\ngetdata()\n.then(data =\u003e {\n  functionThatMightThrow(data);\n})\n.catch(error =\u003e {\n  // One option (more noisy than console.log):\n  console.error(error);\n  // Another option:\n  notifyUserOfError(error);\n  // Another option:\n  reportErrorToService(error);\n  // OR do all three!\n});\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n\n## **Formatting**\nFormatting is subjective. Like many rules herein, there is no hard and fast\nrule that you must follow. The main point is DO NOT ARGUE over formatting.\nThere are [tons of tools](http://standardjs.com/rules.html) to automate this.\nUse one! It's a waste of time and money for engineers to argue over formatting.\n\nFor things that don't fall under the purview of automatic formatting\n(indentation, tabs vs. spaces, double vs. single quotes, etc.) look here\nfor some guidance.\n\n### Use consistent capitalization\nJavaScript is untyped, so capitalization tells you a lot about your variables,\nfunctions, etc. These rules are subjective, so your team can choose whatever\nthey want. The point is, no matter what you all choose, just be consistent.\n\n**Bad:**\n```javascript\nconst DAYS_IN_WEEK = 7;\nconst daysInMonth = 30;\n\nconst songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];\nconst Artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];\n\nfunction eraseDatabase() {}\nfunction restore_database() {}\n\nclass animal {}\nclass Alpaca {}\n```\n\n**Good**:\n```javascript\nconst DAYS_IN_WEEK = 7;\nconst DAYS_IN_MONTH = 30;\n\nconst songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'];\nconst artists = ['ACDC', 'Led Zeppelin', 'The Beatles'];\n\nfunction eraseDatabase() {}\nfunction restoreDatabase() {}\n\nclass Animal {}\nclass Alpaca {}\n```\n**[⬆ back to top](#table-of-contents)**\n\n\n### Function callers and callees should be close\nIf a function calls another, keep those functions vertically close in the source\nfile. Ideally, keep the caller right above the callee. We tend to read code from\ntop-to-bottom, like a newspaper. Because of this, make your code read that way.\n\n**Bad:**\n```javascript\nclass PerformanceReview {\n  constructor(employee) {\n    this.employee = employee;\n  }\n\n  lookupPeers() {\n    return db.lookup(this.employee, 'peers');\n  }\n\n  lookupMananger() {\n    return db.lookup(this.employee, 'manager');\n  }\n\n  getPeerReviews() {\n    const peers = this.lookupPeers();\n    // ...\n  }\n\n  perfReview() {\n    this.getPeerReviews();\n    this.getManagerReview();\n    this.getSelfReview();\n  }\n\n  getManagerReview() {\n    const manager = this.lookupManager();\n  }\n\n  getSelfReview() {\n    // ...\n  }\n}\n\nconst review = new PerformanceReview(user);\nreview.perfReview();\n```\n\n**Good**:\n```javascript\nclass PerformanceReview {\n  constructor(employee) {\n    this.employee = employee;\n  }\n\n  perfReview() {\n    this.getPeerReviews();\n    this.getManagerReview();\n    this.getSelfReview();\n  }\n\n  getPeerReviews() {\n    const peers = this.lookupPeers();\n    // ...\n  }\n\n  lookupPeers() {\n    return db.lookup(this.employee, 'peers');\n  }\n\n  getManagerReview() {\n    const manager = this.lookupManager();\n  }\n\n  lookupMananger() {\n    return db.lookup(this.employee, 'manager');\n  }\n\n  getSelfReview() {\n    // ...\n  }\n}\n\nconst review = new PerformanceReview(employee);\nreview.perfReview();\n```\n\n**[⬆ back to top](#table-of-contents)**\n\n## **Comments**\n### Only comment things that have business logic complexity.\nComments are an apology, not a requirement. Good code *mostly* documents itself.\n\n**Bad:**\n```javascript\nfunction hashIt(data) {\n  // The hash\n  let hash = 0;\n\n  // Length of string\n  const length = data.length;\n\n  // Loop through every character in data\n  for (let i = 0; i \u003c length; i++) {\n    // Get character code.\n    const char = data.charCodeAt(i);\n    // Make the hash\n    hash = ((hash \u003c\u003c 5) - hash) + char;\n    // Convert to 32-bit integer\n    hash = hash \u0026 hash;\n  }\n}\n```\n\n**Good**:\n```javascript\n\nfunction hashIt(data) {\n  let hash = 0;\n  const length = data.length;\n\n  for (let i = 0; i \u003c length; i++) {\n    const char = data.charCodeAt(i);\n    hash = ((hash \u003c\u003c 5) - hash) + char;\n\n    // Convert to 32-bit integer\n    hash = hash \u0026 hash;\n  }\n}\n\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Don't leave commented out code in your codebase\nVersion control exists for a reason. Leave old code in your history.\n\n**Bad:**\n```javascript\ndoStuff();\n// doOtherStuff();\n// doSomeMoreStuff();\n// doSoMuchStuff();\n```\n\n**Good**:\n```javascript\ndoStuff();\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Don't have journal comments\nRemember, use version control! There's no need for dead code, commented code,\nand especially journal comments. Use `git log` to get history!\n\n**Bad:**\n```javascript\n/**\n * 2016-12-20: Removed monads, didn't understand them (RM)\n * 2016-10-01: Improved using special monads (JP)\n * 2016-02-03: Removed type-checking (LI)\n * 2015-03-14: Added combine with type-checking (JR)\n */\nfunction combine(a, b) {\n  return a + b;\n}\n```\n\n**Good**:\n```javascript\nfunction combine(a, b) {\n  return a + b;\n}\n```\n**[⬆ back to top](#table-of-contents)**\n\n### Avoid positional markers\nThey usually just add noise. Let the functions and variable names along with the\nproper indentation and formatting give the visual structure to your code.\n\n**Bad:**\n```javascript\n////////////////////////////////////////////////////////////////////////////////\n// Scope Model Instantiation\n////////////////////////////////////////////////////////////////////////////////\n$scope.model = {\n  menu: 'foo',\n  nav: 'bar'\n};\n\n////////////////////////////////////////////////////////////////////////////////\n// Action setup\n////////////////////////////////////////////////////////////////////////////////\nconst actions = function() {\n  // ...\n}\n```\n\n**Good**:\n```javascript\n$scope.model = {\n  menu: 'foo',\n  nav: 'bar'\n};\n\nconst actions = function() {\n  // ...\n}\n```\n**[⬆ back to top](#table-of-contents)**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkazuma512%2Fclean-code-javascript","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkazuma512%2Fclean-code-javascript","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkazuma512%2Fclean-code-javascript/lists"}