{"id":13394880,"url":"https://github.com/felixge/node-style-guide","last_synced_at":"2025-07-16T12:05:16.219Z","repository":{"id":3747466,"uuid":"4822113","full_name":"felixge/node-style-guide","owner":"felixge","description":"A guide for styling your node.js / JavaScript code. Fork \u0026 adjust to your taste.","archived":false,"fork":false,"pushed_at":"2021-01-24T03:40:33.000Z","size":59,"stargazers_count":5005,"open_issues_count":17,"forks_count":913,"subscribers_count":160,"default_branch":"master","last_synced_at":"2025-07-15T13:38:20.915Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/felixge.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-06-28T15:19:35.000Z","updated_at":"2025-07-11T10:43:26.000Z","dependencies_parsed_at":"2022-08-03T01:30:23.348Z","dependency_job_id":null,"html_url":"https://github.com/felixge/node-style-guide","commit_stats":{"total_commits":52,"total_committers":27,"mean_commits":"1.9259259259259258","dds":0.8461538461538461,"last_synced_commit":"318b044f41d45c8602b272868c833d6d26a2af9b"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/felixge/node-style-guide","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/felixge%2Fnode-style-guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/felixge%2Fnode-style-guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/felixge%2Fnode-style-guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/felixge%2Fnode-style-guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/felixge","download_url":"https://codeload.github.com/felixge/node-style-guide/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/felixge%2Fnode-style-guide/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265502747,"owners_count":23777908,"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":[],"created_at":"2024-07-30T17:01:34.930Z","updated_at":"2025-07-16T12:05:16.166Z","avatar_url":"https://github.com/felixge.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Other","others","Javascript","Platforms"],"sub_categories":["Node.js"],"readme":"# Node.js Style Guide\n\nThis is a guide for writing consistent and aesthetically pleasing node.js code.\nIt is inspired by what is popular within the community, and flavored with some\npersonal opinions.\n\nThere is a .jshintrc which enforces these rules as closely as possible. You can\neither use that and adjust it, or use\n[this script](https://gist.github.com/kentcdodds/11293570) to make your own.\n\nThis guide was created by [Felix Geisendörfer](http://felixge.de/) and is\nlicensed under the [CC BY-SA 3.0](http://creativecommons.org/licenses/by-sa/3.0/)\nlicense. You are encouraged to fork this repository and make adjustments\naccording to your preferences.\n\n![Creative Commons License](http://i.creativecommons.org/l/by-sa/3.0/88x31.png)\n\n## Table of contents\n\n### Formatting\n* [2 Spaces for indentation](#2-spaces-for-indentation)\n* [Newlines](#newlines)\n* [No trailing whitespace](#no-trailing-whitespace)\n* [Use Semicolons](#use-semicolons)\n* [80 characters per line](#80-characters-per-line)\n* [Use single quotes](#use-single-quotes)\n* [Opening braces go on the same line](#opening-braces-go-on-the-same-line)\n* [Declare one variable per var statement](#declare-one-variable-per-var-statement)\n\n### Naming Conventions\n* [Use lowerCamelCase for variables, properties and function names](#use-lowercamelcase-for-variables-properties-and-function-names)\n* [Use UpperCamelCase for class names](#use-uppercamelcase-for-class-names)\n* [Use UPPERCASE for Constants](#use-uppercase-for-constants)\n\n### Variables\n* [Object / Array creation](#object--array-creation)\n\n### Conditionals\n* [Use the === operator](#use-the--operator)\n* [Use multi-line ternary operator](#use-multi-line-ternary-operator)\n* [Use descriptive conditions](#use-descriptive-conditions)\n\n### Functions\n* [Write small functions](#write-small-functions)\n* [Return early from functions](#return-early-from-functions)\n* [Name your closures](#name-your-closures)\n* [No nested closures](#no-nested-closures)\n* [Method chaining](#method-chaining)\n\n### Comments\n* [Use slashes for comments](#use-slashes-for-comments)\n\n### Miscellaneous\n* [Object.freeze, Object.preventExtensions, Object.seal, with, eval](#objectfreeze-objectpreventextensions-objectseal-with-eval)\n* [Requires At Top](#requires-at-top)\n* [Getters and setters](#getters-and-setters)\n* [Do not extend built-in prototypes](#do-not-extend-built-in-prototypes)\n\n## Formatting\n\nYou may want to use [editorconfig.org](http://editorconfig.org/) to enforce the formatting settings in your editor. Use the [Node.js Style Guide .editorconfig file](.editorconfig) to have indentation, newslines and whitespace behavior automatically set to the rules set up below.\n\n### 2 Spaces for indentation\n\nUse 2 spaces for indenting your code and swear an oath to never mix tabs and\nspaces - a special kind of hell is awaiting you otherwise.\n\n### Newlines\n\nUse UNIX-style newlines (`\\n`), and a newline character as the last character\nof a file. Windows-style newlines (`\\r\\n`) are forbidden inside any repository.\n\n### No trailing whitespace\n\nJust like you brush your teeth after every meal, you clean up any trailing\nwhitespace in your JS files before committing. Otherwise the rotten smell of\ncareless neglect will eventually drive away contributors and/or co-workers.\n\n### Use Semicolons\n\nAccording to [scientific research][hnsemicolons], the usage of semicolons is\na core value of our community. Consider the points of [the opposition][], but\nbe a traditionalist when it comes to abusing error correction mechanisms for\ncheap syntactic pleasures.\n\n[the opposition]: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding\n[hnsemicolons]: http://news.ycombinator.com/item?id=1547647\n\n### 80 characters per line\n\nLimit your lines to 80 characters. Yes, screens have gotten much bigger over the\nlast few years, but your brain has not. Use the additional room for split screen,\nyour editor supports that, right?\n\n### Use single quotes\n\nUse single quotes, unless you are writing JSON.\n\n*Right:*\n\n```js\nvar foo = 'bar';\n```\n\n*Wrong:*\n\n```js\nvar foo = \"bar\";\n```\n\n### Opening braces go on the same line\n\nYour opening braces go on the same line as the statement.\n\n*Right:*\n\n```js\nif (true) {\n  console.log('winning');\n}\n```\n\n*Wrong:*\n\n```js\nif (true)\n{\n  console.log('losing');\n}\n```\n\nAlso, notice the use of whitespace before and after the condition statement.\n\n### Declare one variable per var statement\n\nDeclare one variable per var statement, it makes it easier to re-order the\nlines. However, ignore [Crockford][crockfordconvention] when it comes to\ndeclaring variables deeper inside a function, just put the declarations wherever\nthey make sense.\n\n*Right:*\n\n```js\nvar keys   = ['foo', 'bar'];\nvar values = [23, 42];\n\nvar object = {};\nwhile (keys.length) {\n  var key = keys.pop();\n  object[key] = values.pop();\n}\n```\n\n*Wrong:*\n\n```js\nvar keys = ['foo', 'bar'],\n    values = [23, 42],\n    object = {},\n    key;\n\nwhile (keys.length) {\n  key = keys.pop();\n  object[key] = values.pop();\n}\n```\n\n[crockfordconvention]: http://javascript.crockford.com/code.html\n\n## Naming Conventions\n\n### Use lowerCamelCase for variables, properties and function names\n\nVariables, properties and function names should use `lowerCamelCase`.  They\nshould also be descriptive. Single character variables and uncommon\nabbreviations should generally be avoided.\n\n*Right:*\n\n```js\nvar adminUser = db.query('SELECT * FROM users ...');\n```\n\n*Wrong:*\n\n```js\nvar admin_user = db.query('SELECT * FROM users ...');\n```\n\n### Use UpperCamelCase for class names\n\nClass names should be capitalized using `UpperCamelCase`.\n\n*Right:*\n\n```js\nfunction BankAccount() {\n}\n```\n\n*Wrong:*\n\n```js\nfunction bank_Account() {\n}\n```\n\n### Use UPPERCASE for Constants\n\nConstants should be declared as regular variables or static class properties,\nusing all uppercase letters.\n\n*Right:*\n\n```js\nvar SECOND = 1 * 1000;\n\nfunction File() {\n}\nFile.FULL_PERMISSIONS = 0777;\n```\n\n*Wrong:*\n\n```js\nconst SECOND = 1 * 1000;\n\nfunction File() {\n}\nFile.fullPermissions = 0777;\n```\n\n[const]: https://developer.mozilla.org/en/JavaScript/Reference/Statements/const\n\n## Variables\n\n### Object / Array creation\n\nUse trailing commas and put *short* declarations on a single line. Only quote\nkeys when your interpreter complains:\n\n*Right:*\n\n```js\nvar a = ['hello', 'world'];\nvar b = {\n  good: 'code',\n  'is generally': 'pretty',\n};\n```\n\n*Wrong:*\n\n```js\nvar a = [\n  'hello', 'world'\n];\nvar b = {\"good\": 'code'\n        , is generally: 'pretty'\n        };\n```\n\n## Conditionals\n\n### Use the === operator\n\nProgramming is not about remembering [stupid rules][comparisonoperators]. Use\nthe triple equality operator as it will work just as expected.\n\n*Right:*\n\n```js\nvar a = 0;\nif (a !== '') {\n  console.log('winning');\n}\n\n```\n\n*Wrong:*\n\n```js\nvar a = 0;\nif (a == '') {\n  console.log('losing');\n}\n```\n\n[comparisonoperators]: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators\n\n### Use multi-line ternary operator\n\nThe ternary operator should not be used on a single line. Split it up into multiple lines instead.\n\n*Right:*\n\n```js\nvar foo = (a === b)\n  ? 1\n  : 2;\n```\n\n*Wrong:*\n\n```js\nvar foo = (a === b) ? 1 : 2;\n```\n\n### Use descriptive conditions\n\nAny non-trivial conditions should be assigned to a descriptively named variable or function:\n\n*Right:*\n\n```js\nvar isValidPassword = password.length \u003e= 4 \u0026\u0026 /^(?=.*\\d).{4,}$/.test(password);\n\nif (isValidPassword) {\n  console.log('winning');\n}\n```\n\n*Wrong:*\n\n```js\nif (password.length \u003e= 4 \u0026\u0026 /^(?=.*\\d).{4,}$/.test(password)) {\n  console.log('losing');\n}\n```\n\n## Functions\n\n### Write small functions\n\nKeep your functions short. A good function fits on a slide that the people in\nthe last row of a big room can comfortably read. So don't count on them having\nperfect vision and limit yourself to ~15 lines of code per function.\n\n### Return early from functions\n\nTo avoid deep nesting of if-statements, always return a function's value as early\nas possible.\n\n*Right:*\n\n```js\nfunction isPercentage(val) {\n  if (val \u003c 0) {\n    return false;\n  }\n\n  if (val \u003e 100) {\n    return false;\n  }\n\n  return true;\n}\n```\n\n*Wrong:*\n\n```js\nfunction isPercentage(val) {\n  if (val \u003e= 0) {\n    if (val \u003c 100) {\n      return true;\n    } else {\n      return false;\n    }\n  } else {\n    return false;\n  }\n}\n```\n\nOr for this particular example it may also be fine to shorten things even\nfurther:\n\n```js\nfunction isPercentage(val) {\n  var isInRange = (val \u003e= 0 \u0026\u0026 val \u003c= 100);\n  return isInRange;\n}\n```\n\n### Name your closures\n\nFeel free to give your closures a name. It shows that you care about them, and\nwill produce better stack traces, heap and cpu profiles.\n\n*Right:*\n\n```js\nreq.on('end', function onEnd() {\n  console.log('winning');\n});\n```\n\n*Wrong:*\n\n```js\nreq.on('end', function() {\n  console.log('losing');\n});\n```\n\n### No nested closures\n\nUse closures, but don't nest them. Otherwise your code will become a mess.\n\n*Right:*\n\n```js\nsetTimeout(function() {\n  client.connect(afterConnect);\n}, 1000);\n\nfunction afterConnect() {\n  console.log('winning');\n}\n```\n\n*Wrong:*\n\n```js\nsetTimeout(function() {\n  client.connect(function() {\n    console.log('losing');\n  });\n}, 1000);\n```\n\n\n### Method chaining\n\nOne method per line should be used if you want to chain methods.\n\nYou should also indent these methods so it's easier to tell they are part of the same chain.\n\n*Right:*\n\n```js\nUser\n  .findOne({ name: 'foo' })\n  .populate('bar')\n  .exec(function(err, user) {\n    return true;\n  });\n```\n\n*Wrong:*\n\n```js\nUser\n.findOne({ name: 'foo' })\n.populate('bar')\n.exec(function(err, user) {\n  return true;\n});\n\nUser.findOne({ name: 'foo' })\n  .populate('bar')\n  .exec(function(err, user) {\n    return true;\n  });\n\nUser.findOne({ name: 'foo' }).populate('bar')\n.exec(function(err, user) {\n  return true;\n});\n\nUser.findOne({ name: 'foo' }).populate('bar')\n  .exec(function(err, user) {\n    return true;\n  });\n```\n\n## Comments\n\n### Use slashes for comments\n\nUse slashes for both single line and multi line comments. Try to write\ncomments that explain higher level mechanisms or clarify difficult\nsegments of your code. Don't use comments to restate trivial things.\n\n*Right:*\n\n```js\n// 'ID_SOMETHING=VALUE' -\u003e ['ID_SOMETHING=VALUE', 'SOMETHING', 'VALUE']\nvar matches = item.match(/ID_([^\\n]+)=([^\\n]+)/));\n\n// This function has a nasty side effect where a failure to increment a\n// redis counter used for statistics will cause an exception. This needs\n// to be fixed in a later iteration.\nfunction loadUser(id, cb) {\n  // ...\n}\n\nvar isSessionValid = (session.expires \u003c Date.now());\nif (isSessionValid) {\n  // ...\n}\n```\n\n*Wrong:*\n\n```js\n// Execute a regex\nvar matches = item.match(/ID_([^\\n]+)=([^\\n]+)/);\n\n// Usage: loadUser(5, function() { ... })\nfunction loadUser(id, cb) {\n  // ...\n}\n\n// Check if the session is valid\nvar isSessionValid = (session.expires \u003c Date.now());\n// If the session is valid\nif (isSessionValid) {\n  // ...\n}\n```\n\n## Miscellaneous\n\n### Object.freeze, Object.preventExtensions, Object.seal, with, eval\n\nCrazy shit that you will probably never need. Stay away from it.\n\n### Requires At Top\n\nAlways put requires at top of file to clearly illustrate a file's dependencies. Besides giving an overview for others at a quick glance of dependencies and possible memory impact, it allows one to determine if they need a package.json file should they choose to use the file elsewhere.\n\n### Getters and setters\n\nDo not use setters, they cause more problems for people who try to use your\nsoftware than they can solve.\n\nFeel free to use getters that are free from [side effects][sideeffect], like\nproviding a length property for a collection class.\n\n[sideeffect]: http://en.wikipedia.org/wiki/Side_effect_(computer_science)\n\n### Do not extend built-in prototypes\n\nDo not extend the prototype of native JavaScript objects. Your future self will\nbe forever grateful.\n\n*Right:*\n\n```js\nvar a = [];\nif (!a.length) {\n  console.log('winning');\n}\n```\n\n*Wrong:*\n\n```js\nArray.prototype.empty = function() {\n  return !this.length;\n}\n\nvar a = [];\nif (a.empty()) {\n  console.log('losing');\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffelixge%2Fnode-style-guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffelixge%2Fnode-style-guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffelixge%2Fnode-style-guide/lists"}