{"id":4786,"date":"2026-05-11T22:58:58","date_gmt":"2026-05-11T17:28:58","guid":{"rendered":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/"},"modified":"2026-05-11T22:58:58","modified_gmt":"2026-05-11T17:28:58","slug":"10-essential-javascript-best-practices-for-cleaner-code","status":"publish","type":"post","link":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/","title":{"rendered":"10 Essential JavaScript Best Practices for Cleaner Code"},"content":{"rendered":"<p>\/\/ This is the specific block of &#8220;clever&#8221; garbage that took down the<br \/>\n\/\/ payment gateway at 3:00 AM on a Sunday.<br \/>\n\/\/ Node v20.11.1 &#8211; Production Environment<\/p>\n<p>var requestCache = {}; \/\/ Global scope leak<\/p>\n<p>app.use((req, res, next) =&gt; {<br \/>\n    var correlationId = req.headers[&#8216;x-correlation-id&#8217;] || Math.random().toString();<\/p>\n<pre class=\"codehilite\"><code>\/\/ &quot;Clever&quot; optimization to avoid DB lookups\nif (requestCache[correlationId]) {\n    res.send(requestCache[correlationId].payload);\n    \/\/ Missing return statement. Execution continues.\n}\n\ndb.query('SELECT * FROM transactions WHERE id = ?', [req.body.id], (err, result) =&gt; {\n    if (err) {\n        \/\/ No error handling. Just logging to a global variable.\n        lastError = err; \n    }\n\n    new Promise((resolve, reject) =&gt; {\n        \/\/ Wrapping a callback in a promise manually for no reason\n        const processed = transformData(result);\n\n        \/\/ Mutating a global object without a cleanup strategy\n        requestCache[correlationId] = {\n            payload: processed,\n            timestamp: Date.now()\n        };\n\n        resolve(processed);\n    }).then(data =&gt; {\n        res.status(200).json(data);\n    });\n\n    \/\/ Unhandled promise rejection if transformData throws\n});\n<\/code><\/pre>\n<p>});<\/p>\n<pre class=\"codehilite\"><code>## The Global Scope is a Graveyard\n\nLook at the first line. `var requestCache = {};`. This is not just a variable; it is a memory leak masquerading as a feature. In a Node.js environment, the module-level scope persists for the lifetime of the process. By attaching a growing object to this scope, you have effectively created a black hole for the heap. \n\nEvery single request that hit the middleware added a key to this object. Because the &quot;clever&quot; developer who wrote this didn't implement a Time-To-Live (TTL) or a Least Recently Used (LRU) eviction policy, the object grew until the V8 engine hit its default heap limit. \n\nHere is the reality: the garbage collector (GC) cannot reclaim memory that is still reachable. Since `requestCache` is in the global module scope, every entry inside it is considered &quot;reachable.&quot; Even after the HTTP response was sent, the data persisted. This isn't just bad code; it's a fundamental misunderstanding of how the V8 heap is structured. \n\nWhen we ran the post-mortem diagnostics, the heap snapshot was damning.\n\n```text\n# node --inspect-brk index.js\n# In Chrome DevTools:\n# Snapshot 1: 24MB (Startup)\n# Snapshot 2: 840MB (After 10,000 requests)\n# Snapshot 3: 1.4GB (FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory)\n\n(node:45201) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues.\n&lt;--- Last few GCs ---&gt;\n[45201:0x6000000]    15201 ms: Mark-sweep 1380.5 (1420.2) -&gt; 1380.1 (1420.2) MB, 420.1 \/ 0.0 ms  (average mu = 0.152, current mu = 0.002) allocation failure; scavenge might not succeed\n<\/code><\/pre>\n<p>The V8 engine spent 420ms trying to perform a Mark-sweep on a heap that was 99% full of un-evictable garbage. This is why following javascript best practices isn&#8217;t optional; it&#8217;s a matter of keeping the server alive. A simple <code>Map<\/code> with a size check or, better yet, an external store like Redis, would have prevented this. But no, we had to be &#8220;clever.&#8221;<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a0399724462a\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a0399724462a\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#Your_Async_Logic_is_a_Race_Condition_Waiting_to_Happen\" >Your Async Logic is a Race Condition Waiting to Happen<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#The_Immutability_Myth_and_the_Const_Lie\" >The Immutability Myth and the Const Lie<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#Hidden_Classes_and_Why_Your_Object_Mutation_Kills_Performance\" >Hidden Classes and Why Your Object Mutation Kills Performance<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#The_Heap_Snapshot_Doesnt_Lie\" >The Heap Snapshot Doesn&#8217;t Lie<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#Error_Handling_is_Not_an_Afterthought\" >Error Handling is Not an Afterthought<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#The_Cost_of_%E2%80%9CClever%E2%80%9D_One-Liners\" >The Cost of &#8220;Clever&#8221; One-Liners<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#The_Execution_Context_and_the_Event_Loop\" >The Execution Context and the Event Loop<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#Refactoring_the_Memory_Management\" >Refactoring the Memory Management<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#Final_Directives_for_the_Engineering_Team\" >Final Directives for the Engineering Team<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#Related_Articles\" >Related Articles<\/a><\/li><\/ul><\/nav><\/div>\n<h2><span class=\"ez-toc-section\" id=\"Your_Async_Logic_is_a_Race_Condition_Waiting_to_Happen\"><\/span>Your Async Logic is a Race Condition Waiting to Happen<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The middleware uses a mixture of legacy callbacks and &#8220;clever&#8221; manual Promise wrappers. Look at the <code>db.query<\/code> block. It\u2019s a callback. Inside that callback, someone decided to instantiate a <code>new Promise<\/code>. <\/p>\n<p>Listen: if you are manually wrapping existing logic in <code>new Promise<\/code>, you are likely doing it wrong. This specific implementation failed to catch errors in <code>transformData(result)<\/code>. If that function throws an exception, the promise is rejected, but there is no <code>.catch()<\/code> block and no <code>await<\/code> with a <code>try\/catch<\/code>. <\/p>\n<p>In Node.js v20, an unhandled promise rejection will, by default, trigger a process exit if not handled correctly. But even before the crash, we saw the &#8220;Dual Response&#8221; bug. Because the developer forgot to <code>return<\/code> after <code>res.send(requestCache[correlationId].payload)<\/code>, the code continued to execute. It attempted to query the database and send <em>another<\/em> response for the same request.<\/p>\n<pre class=\"codehilite\"><code class=\"language-text\">Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client\n    at ServerResponse.setHeader (node:_http_outgoing:648:11)\n    at ServerResponse.header (express\/lib\/response.js:794:10)\n    at ServerResponse.send (express\/lib\/response.js:174:12)\n<\/code><\/pre>\n<p>This flooded the logs and put unnecessary load on the database. The Event Loop was spinning its wheels processing queries for requests that were already closed. This is the cost of &#8220;clever&#8221; shortcuts. You think you&#8217;re saving a few lines of code, but you&#8217;re actually destroying the predictability of the execution stack.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"The_Immutability_Myth_and_the_Const_Lie\"><\/span>The Immutability Myth and the Const Lie<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>I see this in every code review. A developer uses <code>const<\/code> and thinks they have created an immutable data structure. <\/p>\n<pre class=\"codehilite\"><code class=\"language-javascript\">const config = { db: 'prod', timeout: 5000 };\nconfig.timeout = 0; \/\/ Perfectly valid JS\n<\/code><\/pre>\n<p>In the production failure, a &#8220;clever&#8221; developer used <code>const<\/code> for a shared state object, then proceeded to mutate its properties across different middleware functions. They assumed that because the variable couldn&#8217;t be reassigned, the data was safe. <\/p>\n<p>Here is the reality: <code>const<\/code> only prevents the <em>binding<\/em> from being changed. The underlying object in the heap is still fully mutable. During the outage, one request modified a shared configuration object to set a <code>debug: true<\/code> flag. Because that object was shared (thanks to the global scope obsession), <em>every subsequent request<\/em> started dumping full stack traces and PII into the logs.<\/p>\n<p>If you want immutability, use <code>Object.freeze()<\/code>. But even then, it&#8217;s a shallow freeze. If you have nested objects, you&#8217;re still vulnerable. This is why we use functional patterns where we return <em>new<\/em> objects instead of mutating existing ones. It\u2019s not about being &#8220;pure&#8221;; it&#8217;s about not having the production state corrupted by a stray line of code in a utility function.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Hidden_Classes_and_Why_Your_Object_Mutation_Kills_Performance\"><\/span>Hidden Classes and Why Your Object Mutation Kills Performance<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>We need to talk about the V8 engine and why the <code>requestCache<\/code> object was not just a memory leak, but a performance killer. V8 uses &#8220;Hidden Classes&#8221; (also called Shapes) to optimize object property access. When you create an object, V8 assigns it a hidden class. If you add a property, V8 creates a new hidden class that transitions from the first one.<\/p>\n<p>In the broken code, the <code>requestCache<\/code> object was being treated like a catch-all bucket. Properties were being added dynamically with keys that were random strings (the <code>correlationId<\/code>). <\/p>\n<pre class=\"codehilite\"><code class=\"language-javascript\">\/\/ V8 optimization nightmare\nrequestCache['id_1'] = { ... };\nrequestCache['id_2'] = { ... };\n<\/code><\/pre>\n<p>Because the keys were dynamic and the structure of the values sometimes varied (some had <code>timestamp<\/code>, some didn&#8217;t), V8&#8217;s Inline Caching (IC) failed. The engine could no longer predict the memory offset of the properties. It fell back to &#8220;dictionary mode,&#8221; which is significantly slower. <\/p>\n<p>When we looked at the execution profile, the <code>KeyedLoadIC<\/code> and <code>KeyedStoreIC<\/code> stubs were taking up 15% of the CPU time. That is 15% of our compute power wasted because someone didn&#8217;t want to use a proper data structure. Using a <code>Map<\/code> is one of those &#8220;javascript best&#8221; practices that actually matters for the engine. A <code>Map<\/code> is designed for frequent additions and removals of dynamic keys. An <code>Object<\/code> is designed for a fixed shape. Use the right tool.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"The_Heap_Snapshot_Doesnt_Lie\"><\/span>The Heap Snapshot Doesn&#8217;t Lie<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>During the incident, I took a heap dump. If you haven&#8217;t looked at a heap dump under pressure, you haven&#8217;t lived. It\u2019s a graveyard of strings and leaked closures.<\/p>\n<p>The most offensive part of the dump was the &#8220;Closure&#8221; section. Every time that middleware ran, it created a new closure for the <code>db.query<\/code> callback. That closure captured the <code>req<\/code> and <code>res<\/code> objects. Because the <code>db.query<\/code> was slow and the <code>requestCache<\/code> was holding onto references, we had thousands of <code>IncomingMessage<\/code> and <code>ServerResponse<\/code> objects sitting in memory long after the socket had closed.<\/p>\n<pre class=\"codehilite\"><code class=\"language-text\">(Raw Heap Snapshot Analysis)\nObject Name             | Count  | Shallow Size | Retained Size\n---------------------------------------------------------------\nClosure                 | 45,021 | 3.6 MB       | 450.2 MB\nIncomingMessage (req)   | 12,104 | 2.1 MB       | 210.5 MB\nServerResponse (res)    | 12,104 | 2.4 MB       | 240.8 MB\nsystem \/ Context        | 45,021 | 5.2 MB       | 380.1 MB\n<\/code><\/pre>\n<p>The &#8220;Retained Size&#8221; is what matters. That is the amount of memory that would be freed if that object was deleted. Those closures were holding onto the entire request context. This is why we don&#8217;t nest logic five levels deep. Every level of nesting is another opportunity to capture scope that you don&#8217;t need, preventing the GC from doing its job.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Error_Handling_is_Not_an_Afterthought\"><\/span>Error Handling is Not an Afterthought<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The code had a <code>lastError = err;<\/code> line. What is this? A diary? A log for ghosts? <\/p>\n<p>If an error occurs in a database query, the request must be terminated with a 5xx status code, or it must be retried. Simply assigning it to a global variable does nothing for the user and nothing for the system&#8217;s stability. <\/p>\n<p>Furthermore, the lack of a <code>try\/catch<\/code> block around the <code>transformData<\/code> call meant that any malformed data from the database would crash the entire worker process. We are running Node v20; we have <code>async\/await<\/code>. There is no excuse for this callback-hell-style negligence.<\/p>\n<p>Here is how a professional would have written that block, following actual javascript best practices:<\/p>\n<pre class=\"codehilite\"><code class=\"language-javascript\">app.use(async (req, res, next) =&gt; {\n    const correlationId = req.headers['x-correlation-id'] || crypto.randomUUID();\n\n    try {\n        const cached = await cacheService.get(correlationId);\n        if (cached) {\n            return res.json(cached);\n        }\n\n        const [rows] = await db.execute('SELECT * FROM transactions WHERE id = ?', [req.body.id]);\n        if (!rows.length) {\n            return res.status(404).json({ error: 'Not Found' });\n        }\n\n        const processed = await transformData(rows[0]);\n        await cacheService.set(correlationId, processed, { ttl: 300 });\n\n        res.json(processed);\n    } catch (err) {\n        logger.error({ err, correlationId }, 'Transaction processing failed');\n        next(err); \/\/ Pass to Express error handler\n    }\n});\n<\/code><\/pre>\n<p>Notice the differences. <code>async\/await<\/code> makes the execution flow linear and readable. The <code>return<\/code> statements ensure that we don&#8217;t send multiple responses. The <code>try\/catch<\/code> block ensures that any error\u2014whether from the DB, the transformation, or the cache\u2014is caught and passed to the centralized error handler. The cache is an external service with a TTL. No memory leaks. No &#8220;clever&#8221; manual promise wrappers.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"The_Cost_of_%E2%80%9CClever%E2%80%9D_One-Liners\"><\/span>The Cost of &#8220;Clever&#8221; One-Liners<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The original code used <code>Math.random().toString()<\/code> for a correlation ID. This is a collision nightmare in a high-traffic system. <code>Math.random()<\/code> is not cryptographically secure and has a limited entropy pool. We saw duplicate IDs in the logs, which meant Request B was getting the cached data from Request A. <\/p>\n<p>This is a data leak. This is a security incident. <\/p>\n<p>Stop trying to save three seconds by using a built-in function that isn&#8217;t fit for purpose. Use <code>crypto.randomUUID()<\/code>. It\u2019s built into Node.js. It\u2019s fast. It\u2019s correct. <\/p>\n<p>Also, look at the <code>npm audit<\/code> results for the environment this was running in.<\/p>\n<pre class=\"codehilite\"><code class=\"language-text\"># npm audit\nfound 12 vulnerabilities (4 moderate, 8 high) in 1402 packages\n  High: Prototype Pollution in 'lodash'\n  High: Remote Code Execution in 'qs'\n  Moderate: Denial of Service in 'express'\n<\/code><\/pre>\n<p>We are running outdated, vulnerable versions of core libraries because &#8220;if it ain&#8217;t broke, don&#8217;t fix it.&#8221; Well, it broke. It broke spectacularly. Part of being a Senior Architect is realizing that your code doesn&#8217;t live in a vacuum. It lives in an ecosystem of dependencies that need constant maintenance.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"The_Execution_Context_and_the_Event_Loop\"><\/span>The Execution Context and the Event Loop<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>When the server started lagging, the &#8220;clever&#8221; developer&#8217;s first instinct was to add more workers. This made it worse. Each worker started consuming 1.5GB of RAM, hitting the node&#8217;s total memory limit and triggering the OOM (Out Of Memory) Killer in Linux.<\/p>\n<p>The Event Loop was blocked. When the heap is full, the GC runs constantly. Since the GC is a &#8220;stop-the-world&#8221; operation in many phases, the Event Loop cannot process I\/O. <\/p>\n<p>We monitored the <code>eventLoopDelay<\/code>.<\/p>\n<pre class=\"codehilite\"><code class=\"language-text\"># Monitoring Output\nEvent Loop Delay: 150ms\nEvent Loop Delay: 450ms\nEvent Loop Delay: 1200ms\nEvent Loop Delay: 5000ms (CRASH)\n<\/code><\/pre>\n<p>A delay of 5 seconds means the server is effectively dead. It cannot accept new connections. It cannot heartbeat to the load balancer. The load balancer then marks the instance as unhealthy and kills it, but the new instance just inherits the same &#8220;clever&#8221; code and the same traffic, leading to a cascading failure.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Refactoring_the_Memory_Management\"><\/span>Refactoring the Memory Management<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The global <code>requestCache<\/code> has been removed. In its place, we&#8217;ve implemented a proper multi-layered caching strategy. But more importantly, we&#8217;ve addressed the way we handle object allocation.<\/p>\n<p>We are now using <code>Buffer<\/code> pools for heavy data processing to keep the pressure off the V8 heap. We are using <code>stream.Pipeline<\/code> for data transformation to ensure we aren&#8217;t loading massive database result sets into memory all at once.<\/p>\n<p>Look at this comparison of the &#8220;clever&#8221; way vs. the right way:<\/p>\n<p><strong>Clever Way (Broken):<\/strong><\/p>\n<pre class=\"codehilite\"><code class=\"language-javascript\">const data = await db.query('SELECT * FROM large_table');\nconst processed = data.map(row =&gt; heavyTransform(row));\nres.json(processed); \/\/ Allocates a massive string in the heap\n<\/code><\/pre>\n<p><strong>Right Way (Stable):<\/strong><\/p>\n<pre class=\"codehilite\"><code class=\"language-javascript\">const cursor = db.query('SELECT * FROM large_table').cursor();\ncursor.pipe(new TransformStream({\n    transform(chunk) {\n        this.push(heavyTransform(chunk));\n    }\n})).pipe(res); \/\/ Streams data, constant memory footprint\n<\/code><\/pre>\n<p>The &#8220;Right Way&#8221; uses the same amount of memory whether you are processing 10 rows or 1,000,000 rows. This is what it means to build scalable systems. It\u2019s not about how fast you can write the code; it\u2019s about how the code behaves when the load increases by 100x.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Final_Directives_for_the_Engineering_Team\"><\/span>Final Directives for the Engineering Team<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>I am tired of cleaning up these messes. From this point forward, the following rules are non-negotiable:<\/p>\n<ol>\n<li><strong>No Global State:<\/strong> If I see a variable defined in the module scope that isn&#8217;t a constant configuration value, the PR will be rejected. Use dependency injection or a state management service.<\/li>\n<li><strong>Async\/Await Only:<\/strong> No more nested callbacks. No more manual Promise wrappers. If a library doesn&#8217;t support promises, use <code>util.promisify<\/code>.<\/li>\n<li><strong>Strict Error Handling:<\/strong> Every promise must have a <code>.catch()<\/code> or be inside a <code>try\/catch<\/code>. Every Express middleware must call <code>next(err)<\/code> on failure.<\/li>\n<li><strong>No &#8220;Clever&#8221; Hacks:<\/strong> If you think you&#8217;ve found a &#8220;cool&#8221; way to save a few CPU cycles by bypassing a standard pattern, you are wrong. Follow javascript best practices. The V8 engine is smarter than you; write code that it can optimize.<\/li>\n<li><strong>Mandatory Linting:<\/strong> We are moving to a strict ESLint configuration that forbids the use of <code>var<\/code>, requires <code>await<\/code> for promises, and flags potential memory leaks.<\/li>\n<\/ol>\n<p>The outage cost the company significant revenue and reputation. It was entirely preventable. It wasn&#8217;t caused by a surge in traffic or a hardware failure. It was caused by &#8220;clever&#8221; code written by people who didn&#8217;t respect the runtime.<\/p>\n<p>Read the documentation. Understand the Event Loop. Respect the Heap. Or find another job where &#8220;clever&#8221; is an acceptable substitute for &#8220;correct.&#8221;<\/p>\n<p>&#8220;`bash<br \/>\nnpx eslint . &#8211;config .eslintrc.strict.json &#8211;fix &amp;&amp; npx npm-check-updates -u &amp;&amp; npm install &amp;&amp; node &#8211;trace-warnings &#8211;heap-prof index.js<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Related_Articles\"><\/span>Related Articles<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Explore more insights and best practices:<\/p>\n<ul>\n<li><a href=\"https:\/\/itsupportwale.com\/blog\/javascript-best-practices-write-cleaner-efficient-code\/\">Javascript Best Practices Write Cleaner Efficient Code<\/a><\/li>\n<li><a href=\"https:\/\/itsupportwale.com\/blog\/centos-bootable-usb-on-linux\/\">Centos Bootable Usb On Linux<\/a><\/li>\n<li><a href=\"https:\/\/itsupportwale.com\/blog\/print-awesome-ascii-text-in-linux-terminal\/\">Print Awesome Ascii Text In Linux Terminal<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>\/\/ This is the specific block of &#8220;clever&#8221; garbage that took down the \/\/ payment gateway at 3:00 AM on a Sunday. \/\/ Node v20.11.1 &#8211; Production Environment var requestCache = {}; \/\/ Global scope leak app.use((req, res, next) =&gt; { var correlationId = req.headers[&#8216;x-correlation-id&#8217;] || Math.random().toString(); \/\/ &quot;Clever&quot; optimization to avoid DB lookups if &#8230; <a title=\"10 Essential JavaScript Best Practices for Cleaner Code\" class=\"read-more\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/\" aria-label=\"Read more  on 10 Essential JavaScript Best Practices for Cleaner Code\">Read more<\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4786","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>10 Essential JavaScript Best Practices for Cleaner Code - ITSupportWale<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"10 Essential JavaScript Best Practices for Cleaner Code - ITSupportWale\" \/>\n<meta property=\"og:description\" content=\"\/\/ This is the specific block of &#8220;clever&#8221; garbage that took down the \/\/ payment gateway at 3:00 AM on a Sunday. \/\/ Node v20.11.1 &#8211; Production Environment var requestCache = {}; \/\/ Global scope leak app.use((req, res, next) =&gt; { var correlationId = req.headers[&#8216;x-correlation-id&#8217;] || Math.random().toString(); \/\/ &quot;Clever&quot; optimization to avoid DB lookups if ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/\" \/>\n<meta property=\"og:site_name\" content=\"ITSupportWale\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Itsupportwale-298547177495978\" \/>\n<meta property=\"article:published_time\" content=\"2026-05-11T17:28:58+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2021\/05\/android-chrome-512x512-1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"512\" \/>\n\t<meta property=\"og:image:height\" content=\"512\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Techie\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Techie\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"12 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/\"},\"author\":{\"name\":\"Techie\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#\/schema\/person\/8c5a2b3d36396e0a8fd91ec8242fd46d\"},\"headline\":\"10 Essential JavaScript Best Practices for Cleaner Code\",\"datePublished\":\"2026-05-11T17:28:58+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/\"},\"wordCount\":1741,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/#organization\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/\",\"url\":\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/\",\"name\":\"10 Essential JavaScript Best Practices for Cleaner Code - ITSupportWale\",\"isPartOf\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/#website\"},\"datePublished\":\"2026-05-11T17:28:58+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/itsupportwale.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"10 Essential JavaScript Best Practices for Cleaner Code\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#website\",\"url\":\"https:\/\/itsupportwale.com\/blog\/\",\"name\":\"ITSupportWale\",\"description\":\"Tips, Tricks, Fixed-Errors, Tutorials &amp; Guides\",\"publisher\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/itsupportwale.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#organization\",\"name\":\"itsupportwale\",\"url\":\"https:\/\/itsupportwale.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2023\/09\/cropped-Logo-trans-without-slogan.png\",\"contentUrl\":\"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2023\/09\/cropped-Logo-trans-without-slogan.png\",\"width\":1119,\"height\":144,\"caption\":\"itsupportwale\"},\"image\":{\"@id\":\"https:\/\/itsupportwale.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/Itsupportwale-298547177495978\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/itsupportwale.com\/blog\/#\/schema\/person\/8c5a2b3d36396e0a8fd91ec8242fd46d\",\"name\":\"Techie\",\"sameAs\":[\"https:\/\/itsupportwale.com\",\"iswblogadmin\"],\"url\":\"https:\/\/itsupportwale.com\/blog\/author\/iswblogadmin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"10 Essential JavaScript Best Practices for Cleaner Code - ITSupportWale","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:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/","og_locale":"en_US","og_type":"article","og_title":"10 Essential JavaScript Best Practices for Cleaner Code - ITSupportWale","og_description":"\/\/ This is the specific block of &#8220;clever&#8221; garbage that took down the \/\/ payment gateway at 3:00 AM on a Sunday. \/\/ Node v20.11.1 &#8211; Production Environment var requestCache = {}; \/\/ Global scope leak app.use((req, res, next) =&gt; { var correlationId = req.headers[&#8216;x-correlation-id&#8217;] || Math.random().toString(); \/\/ &quot;Clever&quot; optimization to avoid DB lookups if ... Read more","og_url":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/","og_site_name":"ITSupportWale","article_publisher":"https:\/\/www.facebook.com\/Itsupportwale-298547177495978","article_published_time":"2026-05-11T17:28:58+00:00","og_image":[{"width":512,"height":512,"url":"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2021\/05\/android-chrome-512x512-1.png","type":"image\/png"}],"author":"Techie","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Techie","Est. reading time":"12 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#article","isPartOf":{"@id":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/"},"author":{"name":"Techie","@id":"https:\/\/itsupportwale.com\/blog\/#\/schema\/person\/8c5a2b3d36396e0a8fd91ec8242fd46d"},"headline":"10 Essential JavaScript Best Practices for Cleaner Code","datePublished":"2026-05-11T17:28:58+00:00","mainEntityOfPage":{"@id":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/"},"wordCount":1741,"commentCount":0,"publisher":{"@id":"https:\/\/itsupportwale.com\/blog\/#organization"},"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/","url":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/","name":"10 Essential JavaScript Best Practices for Cleaner Code - ITSupportWale","isPartOf":{"@id":"https:\/\/itsupportwale.com\/blog\/#website"},"datePublished":"2026-05-11T17:28:58+00:00","breadcrumb":{"@id":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/itsupportwale.com\/blog\/10-essential-javascript-best-practices-for-cleaner-code\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/itsupportwale.com\/blog\/"},{"@type":"ListItem","position":2,"name":"10 Essential JavaScript Best Practices for Cleaner Code"}]},{"@type":"WebSite","@id":"https:\/\/itsupportwale.com\/blog\/#website","url":"https:\/\/itsupportwale.com\/blog\/","name":"ITSupportWale","description":"Tips, Tricks, Fixed-Errors, Tutorials &amp; Guides","publisher":{"@id":"https:\/\/itsupportwale.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/itsupportwale.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/itsupportwale.com\/blog\/#organization","name":"itsupportwale","url":"https:\/\/itsupportwale.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/itsupportwale.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2023\/09\/cropped-Logo-trans-without-slogan.png","contentUrl":"https:\/\/itsupportwale.com\/blog\/wp-content\/uploads\/2023\/09\/cropped-Logo-trans-without-slogan.png","width":1119,"height":144,"caption":"itsupportwale"},"image":{"@id":"https:\/\/itsupportwale.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Itsupportwale-298547177495978"]},{"@type":"Person","@id":"https:\/\/itsupportwale.com\/blog\/#\/schema\/person\/8c5a2b3d36396e0a8fd91ec8242fd46d","name":"Techie","sameAs":["https:\/\/itsupportwale.com","iswblogadmin"],"url":"https:\/\/itsupportwale.com\/blog\/author\/iswblogadmin\/"}]}},"_links":{"self":[{"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/posts\/4786","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/comments?post=4786"}],"version-history":[{"count":0,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/posts\/4786\/revisions"}],"wp:attachment":[{"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/media?parent=4786"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/categories?post=4786"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itsupportwale.com\/blog\/wp-json\/wp\/v2\/tags?post=4786"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}