{"id":720,"date":"2016-12-13T12:41:08","date_gmt":"2016-12-13T11:41:08","guid":{"rendered":"https:\/\/blog.risingstack.comjavascript-clean-coding-best-practices-node-js-at-scale\/"},"modified":"2025-10-15T02:37:52","modified_gmt":"2025-10-15T00:37:52","slug":"javascript-clean-coding-best-practices-node-js-at-scale","status":"publish","type":"post","link":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/","title":{"rendered":"JavaScript Clean Coding Best Practices"},"content":{"rendered":"\n<p><strong>Writing clean code is what you must know and do in order to call yourself a professional developer.<\/strong>\u00a0There is no reasonable excuse for doing anything less than your best.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>\u201cEven bad code can function. But if the code isn\u2019t clean, it can bring a development organization to its knees.\u201d \u2014 Robert C. Martin (Uncle Bob)<\/p>\n<\/blockquote>\n\n\n\n<p>In this blog post, we will cover general clean coding principles for naming and using variables &amp; functions, as well as some&nbsp;<strong>JavaScript specific clean coding best practices.<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Node.js at Scale<\/strong>&nbsp;is a collection of articles focusing on the needs of companies with bigger Node.js installations and advanced Node developers. Chapters:<\/p>\n<\/blockquote>\n\n\n\n<p><strong>See all chapters of Node.js at Scale:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Using npm<\/strong>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/blog.risingstack.com\/nodejs-at-scale-npm-best-practices\/\" target=\"_blank\" rel=\"noreferrer noopener\">npm Tricks and Best Practices<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/nodejs-at-scale-npm-publish-tutorial\/\" target=\"_blank\" rel=\"noreferrer noopener\">SemVer and Module Publishing<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/node-js-at-scale-module-system-commonjs-require\/\" target=\"_blank\" rel=\"noreferrer noopener\">Understanding the Module System, CommonJS and require<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Node.js Internals Deep Dive<\/strong>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/blog.risingstack.com\/node-js-at-scale-understanding-node-js-event-loop\/\" target=\"_blank\" rel=\"noreferrer noopener\">The Node.js Event Loop<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/node-js-at-scale-node-js-garbage-collection\/\" target=\"_blank\" rel=\"noreferrer noopener\">Node.js Garbage Collection Explained<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/writing-native-node-js-modules\/\" target=\"_blank\" rel=\"noreferrer noopener\">Writing Native Node.js Modules<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Building with Node.js<\/strong>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/blog.risingstack.com\/node-js-project-structure-tutorial-node-js-at-scale\/\" target=\"_blank\" rel=\"noreferrer noopener\">Advanced Node.js Project Structuring<\/a><\/li>\n\n\n\n<li>JavaScript Clean Coding Best Practices&nbsp;<em>[ this article ]<\/em><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/node-js-async-best-practices-avoiding-callback-hell-node-js-at-scale\/\" target=\"_blank\" rel=\"noreferrer noopener\">Node.js Async Best Practices<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/event-sourcing-with-examples-node-js-at-scale\/\" target=\"_blank\" rel=\"noreferrer noopener\">Event sourcing with Examples<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/cqrs-explained-node-js-at-scale\/\" target=\"_blank\" rel=\"noreferrer noopener\">CQRS (Command Query Responsibility Segregation) Explained<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Testing + Node<\/strong>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/blog.risingstack.com\/getting-node-js-testing-and-tdd-right-node-js-at-scale\/\" target=\"_blank\" rel=\"noreferrer noopener\">Node.js Testing and Getting TDD Right<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/end-to-end-testing-with-nightwatch-js-node-js-at-scale\/\" target=\"_blank\" rel=\"noreferrer noopener\">Node.js End-to-End Testing with Nightwatch.js<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Node.js in Production<\/strong>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/blog.risingstack.com\/monitoring-nodejs-applications-nodejs-at-scale\/\" target=\"_blank\" rel=\"noreferrer noopener\">The Definitive Guide for Monitoring Node.js Applications<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/how-to-debug-nodej-js-with-the-best-tools-available\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Debug Node.js with the Best Tools Available<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/post-mortem-diagnostics-debugging-node-js-at-scale\/\" target=\"_blank\" rel=\"noreferrer noopener\">Node.js Post-Mortem Diagnostics &amp; Debugging<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Node.js + Microservices<\/strong>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/blog.risingstack.com\/distributed-tracing-opentracing-node-js\/\" target=\"_blank\" rel=\"noreferrer noopener\">Distributed Tracing<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/blog.risingstack.com\/building-an-api-gateway-using-nodejs\/\" target=\"_blank\" rel=\"noreferrer noopener\">API Gateways<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><a href=\"https:\/\/risingstack.com\/nodejs-development-consulting-services\/\"><img fetchpriority=\"high\" decoding=\"async\" width=\"1024\" height=\"254\" src=\"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2023\/02\/blog-banner-node-1024x254.png\" alt=\"\" class=\"wp-image-3308\" srcset=\"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2023\/02\/blog-banner-node-1024x254.png 1024w, https:\/\/blog.risingstack.com\/wp-content\/uploads\/2023\/02\/blog-banner-node-300x74.png 300w, https:\/\/blog.risingstack.com\/wp-content\/uploads\/2023\/02\/blog-banner-node-768x190.png 768w, https:\/\/blog.risingstack.com\/wp-content\/uploads\/2023\/02\/blog-banner-node.png 1226w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"firstofallwhatdoescleancodingmean\">First of all, what does clean coding mean?<\/h2>\n\n\n\n<p>Clean coding means that in the first place you write code for your later self and for your co-workers and not for the machine.<\/p>\n\n\n\n<p><strong>Your code must be easily understandable for humans.<\/strong><\/p>\n\n\n\n<p>You know you are working on a clean code when each routine you read turns out to be pretty much what you expected.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/blog-assets.risingstack.com\/2016\/12\/javascript-clean-coding-best-practices-code-review.jpg\" alt=\"JavaSctipr Clean Coding: The only valid measurement of code quality is WTFs\/minute\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"javascriptcleancodingbestpractices\">JavaScript Clean Coding Best Practices<\/h2>\n\n\n\n<p>Now that we know what every developer should aim for, let\u2019s go through the best practices!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"howshouldinamemyvariables\">How should I name my variables?<\/h3>\n\n\n\n<p><strong>Use intention-revealing names<\/strong>&nbsp;and don&#8217;t worry if you have long variable names instead of saving a few keyboard strokes.<\/p>\n\n\n\n<p><strong>If you follow this practice, your names become searchable,<\/strong>&nbsp;which helps a lot when you do refactors or you are just looking for something.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DON'T\nlet d\nlet elapsed\nconst ages = arr.map((i) =&gt; i.age)\n\n\/\/ DO\nlet daysSinceModification\nconst agesOfUsers = users.map((user) =&gt; user.age)\n<\/code><\/pre>\n\n\n\n<p>Also,&nbsp;<strong>make meaningful distinctions<\/strong>&nbsp;and&nbsp;<strong>don&#8217;t add extra, unnecessary nouns<\/strong>&nbsp;to the variable names, like its type (<a href=\"https:\/\/en.wikipedia.org\/wiki\/Hungarian_notation\">hungarian notation<\/a>).<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DON'T\nlet nameString\nlet theUsers\n\n\/\/ DO\nlet name\nlet users\n<\/code><\/pre>\n\n\n\n<p><strong>Make your variable names easy to pronounce,<\/strong>&nbsp;because for the human mind it takes less effort to process.<\/p>\n\n\n\n<p>When you are doing code reviews with your fellow developers, these names are easier to reference.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DON'T\nlet fName, lName\nlet cntr\n\nlet full = false\nif (cart.size &gt; 100) {\n  full = true\n}\n\n\/\/ DO\nlet firstName, lastName\nlet counter\n\nconst MAX_CART_SIZE = 100\n\/\/ ...\nconst isFull = cart.size &gt; MAX_CART_SIZE\n<\/code><\/pre>\n\n\n\n<p>In short, don&#8217;t cause extra mental mapping with your names.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"howshouldiwritemyfunctions\">How should I write my functions?<\/h3>\n\n\n\n<p>Your functions should do one thing only on one level of abstraction.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>Functions should do one thing. They should do it well. They should do it only. \u2014 Robert C. Martin (Uncle Bob)<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DON'T\nfunction getUserRouteHandler (req, res) {\n  const { userId } = req.params\n  \/\/ inline SQL query\n  knex('user')\n    .where({ id: userId })\n    .first()\n    .then((user) =&gt; res.json(user))\n}\n\n\/\/ DO\n\/\/ User model (eg. models\/user.js)\nconst tableName = 'user'\nconst User = {\n  getOne (userId) {\n    return knex(tableName)\n      .where({ id: userId })\n      .first()\n  }\n}\n\n\/\/ route handler (eg. server\/routes\/user\/get.js)\nfunction getUserRouteHandler (req, res) {\n  const { userId } = req.params\n  User.getOne(userId)\n    .then((user) =&gt; res.json(user))\n}\n<\/code><\/pre>\n\n\n\n<p>After you wrote your functions properly, you can test how well you did with&nbsp;<a href=\"https:\/\/blog.risingstack.com\/node-js-tutorial-debugging-async-memory-leaks-cpu-profiling\/\">CPU profiling<\/a>&nbsp;&#8211; which helps you to find bottlenecks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"uselongdescriptivenames\">Use long, descriptive names<\/h3>\n\n\n\n<p><strong>A function name<\/strong>&nbsp;should be a verb or a verb phrase, and it&nbsp;<strong>needs to communicate its intent,<\/strong>&nbsp;as well as the order and intent of the arguments.<\/p>\n\n\n\n<p>A long descriptive name is way better than a short, enigmatic name or a long descriptive comment.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DON'T\n\/**\n * Invite a new user with its email address\n * @param {String} user email address\n *\/\nfunction inv (user) { \/* implementation *\/ }\n\n\/\/ DO\nfunction inviteUser (emailAddress) { \/* implementation *\/ }\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"avoidlongargumentlist\">Avoid long argument list<\/h3>\n\n\n\n<p>Use a single object parameter and destructuring assignment instead. It also makes handling optional parameters much easier.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DON'T\nfunction getRegisteredUsers (fields, include, fromDate, toDate) { \/* implementation *\/ }\ngetRegisteredUsers(&#91;'firstName', 'lastName', 'email'], &#91;'invitedUsers'], '2016-09-26', '2016-12-13')\n\n\/\/ DO\nfunction getRegisteredUsers ({ fields, include, fromDate, toDate }) { \/* implementation *\/ }\ngetRegisteredUsers({\n  fields: &#91;'firstName', 'lastName', 'email'],\n  include: &#91;'invitedUsers'],\n  fromDate: '2016-09-26',\n  toDate: '2016-12-13'\n})\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"reducesideeffects\">Reduce side effects<\/h3>\n\n\n\n<p>Use pure functions without side effects, whenever you can.&nbsp;<strong>They are really easy to use and test.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DON'T\nfunction addItemToCart (cart, item, quantity = 1) {\n  const alreadyInCart = cart.get(item.id) || 0\n  cart.set(item.id, alreadyInCart + quantity)\n  return cart\n}\n\n\/\/ DO\n\/\/ not modifying the original cart\nfunction addItemToCart (cart, item, quantity = 1) {\n  const cartCopy = new Map(cart)\n  const alreadyInCart = cartCopy.get(item.id) || 0\n  cartCopy.set(item.id, alreadyInCart + quantity)\n  return cartCopy\n}\n\n\/\/ or by invert the method location\n\/\/ you can expect that the original object will be mutated\n\/\/ addItemToCart(cart, item, quantity) -&gt; cart.addItem(item, quantity)\nconst cart = new Map()\nObject.assign(cart, {\n  addItem (item, quantity = 1) {\n    const alreadyInCart = this.get(item.id) || 0\n    this.set(item.id, alreadyInCart + quantity)\n    return this\n  }\n})\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"organizeyourfunctionsinafileaccordingtothestepdownrule\">Organize your functions in a file according to the stepdown rule<\/h3>\n\n\n\n<p>Higher level functions should be on top and lower levels below. It makes it natural to read the source code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ DON'T\n\/\/ \"I need the full name for something...\"\nfunction getFullName (user) {\n  return `${user.firstName} ${user.lastName}`\n}\n\nfunction renderEmailTemplate (user) {\n  \/\/ \"oh, here\"\n  const fullName = getFullName(user)\n  return `Dear ${fullName}, ...`\n}\n\n\/\/ DO\nfunction renderEmailTemplate (user) {\n  \/\/ \"I need the full name of the user\"\n  const fullName = getFullName(user)\n  return `Dear ${fullName}, ...`\n}\n\n\/\/ \"I use this for the email template rendering\"\nfunction getFullName (user) {\n  return `${user.firstName} ${user.lastName}`\n}\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"queryormodification\">Query or modification<\/h3>\n\n\n\n<p>Functions should either do something (modify) or answer something (query), but not both.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"everyonelikestowritejavascriptdifferentlywhattodo\">Everyone likes to write JavaScript differently, what to do?<\/h2>\n\n\n\n<p>As JavaScript is dynamic and loosely typed, it is especially prone to programmer errors.<\/p>\n\n\n\n<p><strong>Use project or company wise linter rules and formatting style.<\/strong><\/p>\n\n\n\n<p>The stricter the rules, the less effort will go into pointing out bad formatting in code reviews. It should cover things like consistent naming, indentation size, whitespace placement and even semicolons.<\/p>\n\n\n\n<p>The&nbsp;<a href=\"http:\/\/standardjs.com\/\">standard JS<\/a>&nbsp;style is quite nice to start with, but in my opinion, it isn&#8217;t strict enough. I can&nbsp;<a href=\"https:\/\/github.com\/RisingStack\/multi-process-nodejs-example\/blob\/master\/.eslintrc.yaml\">agree<\/a>&nbsp;most of the rules in the&nbsp;<a href=\"https:\/\/github.com\/airbnb\/javascript\">Airbnb style<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"howtowriteniceasynccode\">How to write nice async code?<\/h2>\n\n\n\n<p>Use&nbsp;<a href=\"https:\/\/blog.risingstack.com\/asynchronous-javascript\/\">Promises<\/a>&nbsp;whenever you can.<\/p>\n\n\n\n<p>Promises are natively available from Node 4. Instead of writing nested callbacks, you can have chainable Promise calls.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ AVOID\nasyncFunc1((err, result1) =&gt; {\n  asyncFunc2(result1, (err, result2) =&gt; {\n    asyncFunc3(result2, (err, result3) =&gt; {\n      console.lor(result3)\n    })\n  })\n})\n\n\/\/ PREFER\nasyncFuncPromise1()\n  .then(asyncFuncPromise2)\n  .then(asyncFuncPromise3)\n  .then((result) =&gt; console.log(result))\n  .catch((err) =&gt; console.error(err))\n<\/code><\/pre>\n\n\n\n<p>Most of the libraries out there have both callback and promise interfaces, prefer the latter. You can even convert callback APIs to promise based one by wrapping them using packages like&nbsp;<a href=\"https:\/\/www.npmjs.com\/package\/es6-promisify\">es6-promisify<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ AVOID\nconst fs = require('fs')\n\nfunction readJSON (filePath, callback) {\n  fs.readFile(filePath, (err, data) =&gt; {\n    if (err) {\n      return callback(err)\n    }\n\n    try {\n      callback(null, JSON.parse(data))\n    } catch (ex) {\n      callback(ex)\n    }\n  })\n}\n\nreadJSON('.\/package.json', (err, pkg) =&gt; { console.log(err, pkg) })\n\n\/\/ PREFER\nconst fs = require('fs')\nconst promisify = require('es6-promisify')\n\nconst readFile = promisify(fs.readFile)\nfunction readJSON (filePath) {\n  return readFile(filePath)\n    .then((data) =&gt; JSON.parse(data))\n}\n\nreadJSON('.\/package.json')\n  .then((pkg) =&gt; console.log(pkg))\n  .catch((err) =&gt; console.error(err))\n<\/code><\/pre>\n\n\n\n<p>The next step would be to use&nbsp;<code>async\/await<\/code>&nbsp;(\u2265 Node 7) or&nbsp;<code>generators<\/code>&nbsp;with&nbsp;<a href=\"https:\/\/www.npmjs.com\/package\/co\"><code>co<\/code><\/a>&nbsp;(\u2265 Node 4) to achieve synchronous like control flows for your asynchronous code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const request = require('request-promise-native')\n\nfunction getExtractFromWikipedia (title) {\n  return request({\n    uri: 'https:\/\/en.wikipedia.org\/w\/api.php',\n    qs: {\n      titles: title,\n      action: 'query',\n      format: 'json',\n      prop: 'extracts',\n      exintro: true,\n      explaintext: true\n    },\n    method: 'GET',\n    json: true\n  })\n    .then((body) =&gt; Object.keys(body.query.pages).map((key) =&gt; body.query.pages&#91;key].extract))\n    .then((extracts) =&gt; extracts&#91;0])\n    .catch((err) =&gt; {\n      console.error('getExtractFromWikipedia() error:', err)\n      throw err\n    })\n} \n\n\/\/ PREFER\nasync function getExtractFromWikipedia (title) {\n  let body\n  try {\n    body = await request({ \/* same parameters as above *\/ })\n  } catch (err) {\n    console.error('getExtractFromWikipedia() error:', err)\n    throw err\n  }\n\n  const extracts = Object.keys(body.query.pages).map((key) =&gt; body.query.pages&#91;key].extract)\n  return extracts&#91;0]\n}\n\n\/\/ or\nconst co = require('co')\n\nconst getExtractFromWikipedia = co.wrap(function * (title) {\n  let body\n  try {\n    body = yield request({ \/* same parameters as above *\/ })\n  } catch (err) {\n    console.error('getExtractFromWikipedia() error:', err)\n    throw err\n  }\n\n  const extracts = Object.keys(body.query.pages).map((key) =&gt; body.query.pages&#91;key].extract)\n  return extracts&#91;0]\n})\n\ngetExtractFromWikipedia('Robert Cecil Martin')\n  .then((robert) =&gt; console.log(robert))\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"howshouldiwriteperformantcode\">How should I write performant code?<\/h2>\n\n\n\n<p>In the first place, you should write clean code, then use&nbsp;<a href=\"https:\/\/blog.risingstack.com\/node-js-tutorial-debugging-async-memory-leaks-cpu-profiling\/\">profiling<\/a>&nbsp;to find performance bottlenecks.<\/p>\n\n\n\n<p>Never try to write performant and smart code first, instead, optimize the code when you need to and refer to true impact instead of micro-benchmarks.<\/p>\n\n\n\n<p>Although, there are some straightforward scenarios like eagerly initializing what you can (eg. joi schemas in route handlers, which would be used in every request and adds serious overhead if recreated every time) and using asynchronous instead of blocking code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Q&amp;A: JavaScript Clean Coding<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What does \u201cclean\u201d mean here?<\/h3>\n\n\n\n<p>You write for future you and your teammates\u2014not the machine. Code should read the way you expect when you open a file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Variable names: short or long?<\/h3>\n\n\n\n<p>Prefer intention-revealing, pronounceable, searchable names\u2014even if they\u2019re long. Avoid meaningless letters and Hungarian notation. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How should I structure functions?<\/h3>\n\n\n\n<p>One thing, one level of abstraction. Keep data access out of route handlers; move it to a model\/helper and call it from the handler.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Function names: any rules of thumb?<\/h3>\n\n\n\n<p>Use descriptive verb phrases. A long, clear name beats a short name plus a comment. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What about long parameter lists?<\/h3>\n\n\n\n<p>Don\u2019t. Take an options object and destructure. It documents intent and makes optional params sane. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Side effects?<\/h3>\n\n\n\n<p>Prefer pure functions. If mutation is intended, make it explicit (e.g., a method on the object). <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">File layout?<\/h3>\n\n\n\n<p>Follow the \u201cstepdown rule\u201d: higher-level functions first, helpers below\u2014so reading top-to-bottom matches your mental model. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Query vs modification?<\/h3>\n\n\n\n<p>A function should either answer a question or change state\u2014not both. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">\u201cEveryone codes differently\u201d\u2014how do we keep consistency?<\/h3>\n\n\n\n<p>Enforce it. Adopt strict linter\/formatter rules (e.g., Standard or, better, Airbnb) to remove style noise from reviews. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Async style to prefer?<\/h3>\n\n\n\n<p>Use Promises (native), then <code>async\/await<\/code> for synchronous-looking flows; avoid callback pyramids. Promisify legacy APIs when needed. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Performance guidance?<\/h3>\n\n\n\n<p>Write clean code first; profile to find real bottlenecks. Don\u2019t micro-optimize blindly. Eagerly initialize expensive, always-used bits (e.g., validation schemas) and avoid blocking calls.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"nextupinnodejsatscale\">Next up in Node.js at Scale<\/h2>\n\n\n\n<p>In the next episode of this series, we\u2019ll discuss advanced&nbsp;<a href=\"https:\/\/blog.risingstack.com\/node-js-async-best-practices-avoiding-callback-hell-node-js-at-scale\/\">Node.js async best practices and avoiding the callback hell<\/a>!<\/p>\n\n\n\n<p><strong>If you have any questions regarding clean coding, don\u2019t hesitate and let me know in the comments!<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post covers general clean coding guidelines for naming and using variables &#038; functions, as well as some JavaScript specific clean coding best practices<\/p>\n","protected":false},"author":1,"featured_media":721,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27],"tags":[14],"class_list":["post-720","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","tag-edited"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>JavaScript Clean Coding Best Practices - RisingStack Engineering<\/title>\n<meta name=\"description\" content=\"This post covers general clean coding guidelines for naming and using variables &amp; functions, as well as some JavaScript specific clean coding best practices\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"JavaScript Clean Coding Best Practices - RisingStack Engineering\" \/>\n<meta property=\"og:description\" content=\"This post covers general clean coding guidelines for naming and using variables &amp; functions, as well as some JavaScript specific clean coding best practices\" \/>\n<meta property=\"og:url\" content=\"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/\" \/>\n<meta property=\"og:site_name\" content=\"RisingStack Engineering\" \/>\n<meta property=\"article:published_time\" content=\"2016-12-13T11:41:08+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-10-15T00:37:52+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2021\/07\/javascript-clean-coding-best-practices.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"630\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"RisingStack Engineering\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"RisingStack Engineering\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/\"},\"author\":{\"name\":\"RisingStack Engineering\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#\\\/schema\\\/person\\\/7cd795f2e5173258661ba604144b0b22\"},\"headline\":\"JavaScript Clean Coding Best Practices\",\"datePublished\":\"2016-12-13T11:41:08+00:00\",\"dateModified\":\"2025-10-15T00:37:52+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/\"},\"wordCount\":1231,\"publisher\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/blog.risingstack.com\\\/wp-content\\\/uploads\\\/2021\\\/07\\\/javascript-clean-coding-best-practices.png\",\"keywords\":[\"edited\"],\"articleSection\":[\"JavaScript\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/\",\"url\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/\",\"name\":\"JavaScript Clean Coding Best Practices - RisingStack Engineering\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/blog.risingstack.com\\\/wp-content\\\/uploads\\\/2021\\\/07\\\/javascript-clean-coding-best-practices.png\",\"datePublished\":\"2016-12-13T11:41:08+00:00\",\"dateModified\":\"2025-10-15T00:37:52+00:00\",\"description\":\"This post covers general clean coding guidelines for naming and using variables & functions, as well as some JavaScript specific clean coding best practices\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/#primaryimage\",\"url\":\"https:\\\/\\\/blog.risingstack.com\\\/wp-content\\\/uploads\\\/2021\\\/07\\\/javascript-clean-coding-best-practices.png\",\"contentUrl\":\"https:\\\/\\\/blog.risingstack.com\\\/wp-content\\\/uploads\\\/2021\\\/07\\\/javascript-clean-coding-best-practices.png\",\"width\":1200,\"height\":630},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/javascript-clean-coding-best-practices-node-js-at-scale\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/blog.risingstack.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JavaScript Clean Coding Best Practices\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#website\",\"url\":\"https:\\\/\\\/blog.risingstack.com\\\/\",\"name\":\"RisingStack Engineering\",\"description\":\"Node.js Tutorials &amp; Resources\",\"publisher\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/blog.risingstack.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#organization\",\"name\":\"RisingStack Engineering\",\"url\":\"https:\\\/\\\/blog.risingstack.com\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/blog.risingstack.com\\\/wp-content\\\/uploads\\\/2021\\\/05\\\/logo-white-f0fca36fce94ceacd3d608caa6649361-1.svg\",\"contentUrl\":\"https:\\\/\\\/blog.risingstack.com\\\/wp-content\\\/uploads\\\/2021\\\/05\\\/logo-white-f0fca36fce94ceacd3d608caa6649361-1.svg\",\"width\":180,\"height\":45,\"caption\":\"RisingStack Engineering\"},\"image\":{\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/blog.risingstack.com\\\/#\\\/schema\\\/person\\\/7cd795f2e5173258661ba604144b0b22\",\"name\":\"RisingStack Engineering\",\"url\":\"https:\\\/\\\/blog.risingstack.com\\\/author\\\/coolsp\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"JavaScript Clean Coding Best Practices - RisingStack Engineering","description":"This post covers general clean coding guidelines for naming and using variables & functions, as well as some JavaScript specific clean coding best practices","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/","og_locale":"en_US","og_type":"article","og_title":"JavaScript Clean Coding Best Practices - RisingStack Engineering","og_description":"This post covers general clean coding guidelines for naming and using variables & functions, as well as some JavaScript specific clean coding best practices","og_url":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/","og_site_name":"RisingStack Engineering","article_published_time":"2016-12-13T11:41:08+00:00","article_modified_time":"2025-10-15T00:37:52+00:00","og_image":[{"width":1200,"height":630,"url":"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2021\/07\/javascript-clean-coding-best-practices.png","type":"image\/png"}],"author":"RisingStack Engineering","twitter_card":"summary_large_image","twitter_misc":{"Written by":"RisingStack Engineering","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/#article","isPartOf":{"@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/"},"author":{"name":"RisingStack Engineering","@id":"https:\/\/blog.risingstack.com\/#\/schema\/person\/7cd795f2e5173258661ba604144b0b22"},"headline":"JavaScript Clean Coding Best Practices","datePublished":"2016-12-13T11:41:08+00:00","dateModified":"2025-10-15T00:37:52+00:00","mainEntityOfPage":{"@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/"},"wordCount":1231,"publisher":{"@id":"https:\/\/blog.risingstack.com\/#organization"},"image":{"@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/#primaryimage"},"thumbnailUrl":"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2021\/07\/javascript-clean-coding-best-practices.png","keywords":["edited"],"articleSection":["JavaScript"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/","url":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/","name":"JavaScript Clean Coding Best Practices - RisingStack Engineering","isPartOf":{"@id":"https:\/\/blog.risingstack.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/#primaryimage"},"image":{"@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/#primaryimage"},"thumbnailUrl":"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2021\/07\/javascript-clean-coding-best-practices.png","datePublished":"2016-12-13T11:41:08+00:00","dateModified":"2025-10-15T00:37:52+00:00","description":"This post covers general clean coding guidelines for naming and using variables & functions, as well as some JavaScript specific clean coding best practices","breadcrumb":{"@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/#primaryimage","url":"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2021\/07\/javascript-clean-coding-best-practices.png","contentUrl":"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2021\/07\/javascript-clean-coding-best-practices.png","width":1200,"height":630},{"@type":"BreadcrumbList","@id":"https:\/\/blog.risingstack.com\/javascript-clean-coding-best-practices-node-js-at-scale\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/blog.risingstack.com\/"},{"@type":"ListItem","position":2,"name":"JavaScript Clean Coding Best Practices"}]},{"@type":"WebSite","@id":"https:\/\/blog.risingstack.com\/#website","url":"https:\/\/blog.risingstack.com\/","name":"RisingStack Engineering","description":"Node.js Tutorials &amp; Resources","publisher":{"@id":"https:\/\/blog.risingstack.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/blog.risingstack.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/blog.risingstack.com\/#organization","name":"RisingStack Engineering","url":"https:\/\/blog.risingstack.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blog.risingstack.com\/#\/schema\/logo\/image\/","url":"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2021\/05\/logo-white-f0fca36fce94ceacd3d608caa6649361-1.svg","contentUrl":"https:\/\/blog.risingstack.com\/wp-content\/uploads\/2021\/05\/logo-white-f0fca36fce94ceacd3d608caa6649361-1.svg","width":180,"height":45,"caption":"RisingStack Engineering"},"image":{"@id":"https:\/\/blog.risingstack.com\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/blog.risingstack.com\/#\/schema\/person\/7cd795f2e5173258661ba604144b0b22","name":"RisingStack Engineering","url":"https:\/\/blog.risingstack.com\/author\/coolsp\/"}]}},"_links":{"self":[{"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/posts\/720","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/comments?post=720"}],"version-history":[{"count":2,"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/posts\/720\/revisions"}],"predecessor-version":[{"id":4616,"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/posts\/720\/revisions\/4616"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/media\/721"}],"wp:attachment":[{"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/media?parent=720"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/categories?post=720"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.risingstack.com\/wp-json\/wp\/v2\/tags?post=720"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}