Skip to content

Instantly share code, notes, and snippets.

@SarveshKadam
Created December 4, 2020 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SarveshKadam/ff5aa1ca9ecc67d2fe6b49b660000817 to your computer and use it in GitHub Desktop.
Save SarveshKadam/ff5aa1ca9ecc67d2fe6b49b660000817 to your computer and use it in GitHub Desktop.
[
{
"common": {
"repoName": "clean-code-javascript",
"created_at": "Nov 26, 2016",
"user": {
"username": "ryanmcdermott",
"profile_image_url": "https://avatars1.githubusercontent.com/u/5114666?v=4"
},
"branch": "master"
},
"htmlValue": "<h1 id=\"cleancodejavascript\">clean-code-javascript</h1>\n<h2 id=\"tableofcontents\">Table of Contents</h2>\n<ol>\n<li><a href=\"#introduction\">Introduction</a></li>\n<li><a href=\"#variables\">Variables</a></li>\n<li><a href=\"#functions\">Functions</a></li>\n<li><a href=\"#objects-and-data-structures\">Objects and Data Structures</a></li>\n<li><a href=\"#classes\">Classes</a></li>\n<li><a href=\"#solid\">SOLID</a></li>\n<li><a href=\"#testing\">Testing</a></li>\n<li><a href=\"#concurrency\">Concurrency</a></li>\n<li><a href=\"#error-handling\">Error Handling</a></li>\n<li><a href=\"#formatting\">Formatting</a></li>\n<li><a href=\"#comments\">Comments</a></li>\n<li><a href=\"#translation\">Translation</a></li>\n</ol>\n<h2 id=\"introduction\">Introduction</h2>\n<p><img src=\"https://www.osnews.com/images/comics/wtfm.jpg\" alt=\"Humorous image of software quality estimation as a count of how many expletives\nyou shout when reading code\" /></p>\n<p>Software engineering principles, from Robert C. Martin's book\n<a href=\"https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882\"><em>Clean Code</em></a>,\nadapted for JavaScript. This is not a style guide. It's a guide to producing\n<a href=\"https://github.com/ryanmcdermott/3rs-of-software-architecture\">readable, reusable, and refactorable</a> software in JavaScript.</p>\n<p>Not every principle herein has to be strictly followed, and even fewer will be\nuniversally agreed upon. These are guidelines and nothing more, but they are\nones codified over many years of collective experience by the authors of\n<em>Clean Code</em>.</p>\n<p>Our craft of software engineering is just a bit over 50 years old, and we are\nstill learning a lot. When software architecture is as old as architecture\nitself, maybe then we will have harder rules to follow. For now, let these\nguidelines serve as a touchstone by which to assess the quality of the\nJavaScript code that you and your team produce.</p>\n<p>One more thing: knowing these won't immediately make you a better software\ndeveloper, and working with them for many years doesn't mean you won't make\nmistakes. Every piece of code starts as a first draft, like wet clay getting\nshaped into its final form. Finally, we chisel away the imperfections when\nwe review it with our peers. Don't beat yourself up for first drafts that need\nimprovement. Beat up the code instead!</p>\n<h2 id=\"variables\"><strong>Variables</strong></h2>\n<h3 id=\"usemeaningfulandpronounceablevariablenames\">Use meaningful and pronounceable variable names</h3>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const yyyymmdstr = moment().format(\"YYYY/MM/DD\");\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">const currentDate = moment().format(\"YYYY/MM/DD\");\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"usethesamevocabularyforthesametypeofvariable\">Use the same vocabulary for the same type of variable</h3>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">getUserInfo();\ngetClientData();\ngetCustomerRecord();\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">getUser();\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"usesearchablenames\">Use searchable names</h3>\n<p>We will read more code than we will ever write. It's important that the code we\ndo write is readable and searchable. By <em>not</em> naming variables that end up\nbeing meaningful for understanding our program, we hurt our readers.\nMake your names searchable. Tools like\n<a href=\"https://github.com/danielstjules/buddy.js\">buddy.js</a> and\n<a href=\"https://github.com/eslint/eslint/blob/660e0918933e6e7fede26bc675a0763a6b357c94/docs/rules/no-magic-numbers.md\">ESLint</a>\ncan help identify unnamed constants.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">// What the heck is 86400000 for?\nsetTimeout(blastOff, 86400000);\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">// Declare them as capitalized named constants.\nconst MILLISECONDS_IN_A_DAY = 60 * 60 * 24 * 1000; //86400000;\n\nsetTimeout(blastOff, MILLISECONDS_IN_A_DAY);\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"useexplanatoryvariables\">Use explanatory variables</h3>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const address = \"One Infinite Loop, Cupertino 95014\";\nconst cityZipCodeRegex = /^[^,\\\\]+[,\\\\\\s]+(.+?)\\s*(\\d{5})?$/;\nsaveCityZipCode(\n address.match(cityZipCodeRegex)[1],\n address.match(cityZipCodeRegex)[2]\n);\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">const address = \"One Infinite Loop, Cupertino 95014\";\nconst cityZipCodeRegex = /^[^,\\\\]+[,\\\\\\s]+(.+?)\\s*(\\d{5})?$/;\nconst [_, city, zipCode] = address.match(cityZipCodeRegex) || [];\nsaveCityZipCode(city, zipCode);\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"avoidmentalmapping\">Avoid Mental Mapping</h3>\n<p>Explicit is better than implicit.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const locations = [\"Austin\", \"New York\", \"San Francisco\"];\nlocations.forEach(l =&gt; {\n doStuff();\n doSomeOtherStuff();\n // ...\n // ...\n // ...\n // Wait, what is `l` for again?\n dispatch(l);\n});\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">const locations = [\"Austin\", \"New York\", \"San Francisco\"];\nlocations.forEach(location =&gt; {\n doStuff();\n doSomeOtherStuff();\n // ...\n // ...\n // ...\n dispatch(location);\n});\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"dontaddunneededcontext\">Don't add unneeded context</h3>\n<p>If your class/object name tells you something, don't repeat that in your\nvariable name.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const Car = {\n carMake: \"Honda\",\n carModel: \"Accord\",\n carColor: \"Blue\"\n};\n\nfunction paintCar(car) {\n car.carColor = \"Red\";\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">const Car = {\n make: \"Honda\",\n model: \"Accord\",\n color: \"Blue\"\n};\n\nfunction paintCar(car) {\n car.color = \"Red\";\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"usedefaultargumentsinsteadofshortcircuitingorconditionals\">Use default arguments instead of short circuiting or conditionals</h3>\n<p>Default arguments are often cleaner than short circuiting. Be aware that if you\nuse them, your function will only provide default values for <code>undefined</code>\narguments. Other \"falsy\" values such as <code>''</code>, <code>\"\"</code>, <code>false</code>, <code>null</code>, <code>0</code>, and\n<code>NaN</code>, will not be replaced by a default value.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function createMicrobrewery(name) {\n const breweryName = name || \"Hipster Brew Co.\";\n // ...\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function createMicrobrewery(name = \"Hipster Brew Co.\") {\n // ...\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"functions\"><strong>Functions</strong></h2>\n<h3 id=\"functionarguments2orfewerideally\">Function arguments (2 or fewer ideally)</h3>\n<p>Limiting the amount of function parameters is incredibly important because it\nmakes testing your function easier. Having more than three leads to a\ncombinatorial explosion where you have to test tons of different cases with\neach separate argument.</p>\n<p>One or two arguments is the ideal case, and three should be avoided if possible.\nAnything more than that should be consolidated. Usually, if you have\nmore than two arguments then your function is trying to do too much. In cases\nwhere it's not, most of the time a higher-level object will suffice as an\nargument.</p>\n<p>Since JavaScript allows you to make objects on the fly, without a lot of class\nboilerplate, you can use an object if you are finding yourself needing a\nlot of arguments.</p>\n<p>To make it obvious what properties the function expects, you can use the ES2015/ES6\ndestructuring syntax. This has a few advantages:</p>\n<ol>\n<li>When someone looks at the function signature, it's immediately clear what\nproperties are being used.</li>\n<li>It can be used to simulate named parameters.</li>\n<li>Destructuring also clones the specified primitive values of the argument\nobject passed into the function. This can help prevent side effects. Note:\nobjects and arrays that are destructured from the argument object are NOT\ncloned.</li>\n<li>Linters can warn you about unused properties, which would be impossible\nwithout destructuring.</li>\n</ol>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function createMenu(title, body, buttonText, cancellable) {\n // ...\n}\n\ncreateMenu(\"Foo\", \"Bar\", \"Baz\", true);\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function createMenu({ title, body, buttonText, cancellable }) {\n // ...\n}\n\ncreateMenu({\n title: \"Foo\",\n body: \"Bar\",\n buttonText: \"Baz\",\n cancellable: true\n});\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"functionsshoulddoonething\">Functions should do one thing</h3>\n<p>This is by far the most important rule in software engineering. When functions\ndo more than one thing, they are harder to compose, test, and reason about.\nWhen you can isolate a function to just one action, it can be refactored\neasily and your code will read much cleaner. If you take nothing else away from\nthis guide other than this, you'll be ahead of many developers.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function emailClients(clients) {\n clients.forEach(client =&gt; {\n const clientRecord = database.lookup(client);\n if (clientRecord.isActive()) {\n email(client);\n }\n });\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function emailActiveClients(clients) {\n clients.filter(isActiveClient).forEach(email);\n}\n\nfunction isActiveClient(client) {\n const clientRecord = database.lookup(client);\n return clientRecord.isActive();\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"functionnamesshouldsaywhattheydo\">Function names should say what they do</h3>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function addToDate(date, month) {\n // ...\n}\n\nconst date = new Date();\n\n// It's hard to tell from the function name what is added\naddToDate(date, 1);\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function addMonthToDate(month, date) {\n // ...\n}\n\nconst date = new Date();\naddMonthToDate(1, date);\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"functionsshouldonlybeonelevelofabstraction\">Functions should only be one level of abstraction</h3>\n<p>When you have more than one level of abstraction your function is usually\ndoing too much. Splitting up functions leads to reusability and easier\ntesting.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function parseBetterJSAlternative(code) {\n const REGEXES = [\n // ...\n ];\n\n const statements = code.split(\" \");\n const tokens = [];\n REGEXES.forEach(REGEX =&gt; {\n statements.forEach(statement =&gt; {\n // ...\n });\n });\n\n const ast = [];\n tokens.forEach(token =&gt; {\n // lex...\n });\n\n ast.forEach(node =&gt; {\n // parse...\n });\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function parseBetterJSAlternative(code) {\n const tokens = tokenize(code);\n const syntaxTree = parse(tokens);\n syntaxTree.forEach(node =&gt; {\n // parse...\n });\n}\n\nfunction tokenize(code) {\n const REGEXES = [\n // ...\n ];\n\n const statements = code.split(\" \");\n const tokens = [];\n REGEXES.forEach(REGEX =&gt; {\n statements.forEach(statement =&gt; {\n tokens.push(/* ... */);\n });\n });\n\n return tokens;\n}\n\nfunction parse(tokens) {\n const syntaxTree = [];\n tokens.forEach(token =&gt; {\n syntaxTree.push(/* ... */);\n });\n\n return syntaxTree;\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"removeduplicatecode\">Remove duplicate code</h3>\n<p>Do your absolute best to avoid duplicate code. Duplicate code is bad because it\nmeans that there's more than one place to alter something if you need to change\nsome logic.</p>\n<p>Imagine if you run a restaurant and you keep track of your inventory: all your\ntomatoes, onions, garlic, spices, etc. If you have multiple lists that\nyou keep this on, then all have to be updated when you serve a dish with\ntomatoes in them. If you only have one list, there's only one place to update!</p>\n<p>Oftentimes you have duplicate code because you have two or more slightly\ndifferent things, that share a lot in common, but their differences force you\nto have two or more separate functions that do much of the same things. Removing\nduplicate code means creating an abstraction that can handle this set of\ndifferent things with just one function/module/class.</p>\n<p>Getting the abstraction right is critical, that's why you should follow the\nSOLID principles laid out in the <em>Classes</em> section. Bad abstractions can be\nworse than duplicate code, so be careful! Having said this, if you can make\na good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself\nupdating multiple places anytime you want to change one thing.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function showDeveloperList(developers) {\n developers.forEach(developer =&gt; {\n const expectedSalary = developer.calculateExpectedSalary();\n const experience = developer.getExperience();\n const githubLink = developer.getGithubLink();\n const data = {\n expectedSalary,\n experience,\n githubLink\n };\n\n render(data);\n });\n}\n\nfunction showManagerList(managers) {\n managers.forEach(manager =&gt; {\n const expectedSalary = manager.calculateExpectedSalary();\n const experience = manager.getExperience();\n const portfolio = manager.getMBAProjects();\n const data = {\n expectedSalary,\n experience,\n portfolio\n };\n\n render(data);\n });\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function showEmployeeList(employees) {\n employees.forEach(employee =&gt; {\n const expectedSalary = employee.calculateExpectedSalary();\n const experience = employee.getExperience();\n\n const data = {\n expectedSalary,\n experience\n };\n\n switch (employee.type) {\n case \"manager\":\n data.portfolio = employee.getMBAProjects();\n break;\n case \"developer\":\n data.githubLink = employee.getGithubLink();\n break;\n }\n\n render(data);\n });\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"setdefaultobjectswithobjectassign\">Set default objects with Object.assign</h3>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const menuConfig = {\n title: null,\n body: \"Bar\",\n buttonText: null,\n cancellable: true\n};\n\nfunction createMenu(config) {\n config.title = config.title || \"Foo\";\n config.body = config.body || \"Bar\";\n config.buttonText = config.buttonText || \"Baz\";\n config.cancellable =\n config.cancellable !== undefined ? config.cancellable : true;\n}\n\ncreateMenu(menuConfig);\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">const menuConfig = {\n title: \"Order\",\n // User did not include 'body' key\n buttonText: \"Send\",\n cancellable: true\n};\n\nfunction createMenu(config) {\n let finalConfig = Object.assign(\n {\n title: \"Foo\",\n body: \"Bar\",\n buttonText: \"Baz\",\n cancellable: true\n },\n config\n );\n return finalConfig\n // config now equals: {title: \"Order\", body: \"Bar\", buttonText: \"Send\", cancellable: true}\n // ...\n}\n\ncreateMenu(menuConfig);\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"dontuseflagsasfunctionparameters\">Don't use flags as function parameters</h3>\n<p>Flags tell your user that this function does more than one thing. Functions should do one thing. Split out your functions if they are following different code paths based on a boolean.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function createFile(name, temp) {\n if (temp) {\n fs.create(`https://raw.githubusercontent.com/ryanmcdermott/clean-code-javascript/master/temp/${name}`);\n } else {\n fs.create(name);\n }\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function createFile(name) {\n fs.create(name);\n}\n\nfunction createTempFile(name) {\n createFile(`https://raw.githubusercontent.com/ryanmcdermott/clean-code-javascript/master/temp/${name}`);\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"avoidsideeffectspart1\">Avoid Side Effects (part 1)</h3>\n<p>A function produces a side effect if it does anything other than take a value in\nand return another value or values. A side effect could be writing to a file,\nmodifying some global variable, or accidentally wiring all your money to a\nstranger.</p>\n<p>Now, you do need to have side effects in a program on occasion. Like the previous\nexample, you might need to write to a file. What you want to do is to\ncentralize where you are doing this. Don't have several functions and classes\nthat write to a particular file. Have one service that does it. One and only one.</p>\n<p>The main point is to avoid common pitfalls like sharing state between objects\nwithout any structure, using mutable data types that can be written to by anything,\nand not centralizing where your side effects occur. If you can do this, you will\nbe happier than the vast majority of other programmers.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">// Global variable referenced by following function.\n// If we had another function that used this name, now it'd be an array and it could break it.\nlet name = \"Ryan McDermott\";\n\nfunction splitIntoFirstAndLastName() {\n name = name.split(\" \");\n}\n\nsplitIntoFirstAndLastName();\n\nconsole.log(name); // ['Ryan', 'McDermott'];\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function splitIntoFirstAndLastName(name) {\n return name.split(\" \");\n}\n\nconst name = \"Ryan McDermott\";\nconst newName = splitIntoFirstAndLastName(name);\n\nconsole.log(name); // 'Ryan McDermott';\nconsole.log(newName); // ['Ryan', 'McDermott'];\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"avoidsideeffectspart2\">Avoid Side Effects (part 2)</h3>\n<p>In JavaScript, some values are unchangeable (immutable) and some are changeable \n(mutable). Objects and arrays are two kinds of mutable values so it's important \nto handle them carefully when they're passed as parameters to a function. A \nJavaScript function can change an object's properties or alter the contents of \nan array which could easily cause bugs elsewhere.</p>\n<p>Suppose there's a function that accepts an array parameter representing a \nshopping cart. If the function makes a change in that shopping cart array - \nby adding an item to purchase, for example - then any other function that \nuses that same <code>cart</code> array will be affected by this addition. That may be \ngreat, however it could also be bad. Let's imagine a bad situation:</p>\n<p>The user clicks the \"Purchase\" button which calls a <code>purchase</code> function that\nspawns a network request and sends the <code>cart</code> array to the server. Because\nof a bad network connection, the <code>purchase</code> function has to keep retrying the\nrequest. Now, what if in the meantime the user accidentally clicks an \"Add to Cart\"\nbutton on an item they don't actually want before the network request begins?\nIf that happens and the network request begins, then that purchase function\nwill send the accidentally added item because the <code>cart</code> array was modified.</p>\n<p>A great solution would be for the <code>addItemToCart</code> function to always clone the \n<code>cart</code>, edit it, and return the clone. This would ensure that functions that are still\nusing the old shopping cart wouldn't be affected by the changes.</p>\n<p>Two caveats to mention to this approach:</p>\n<ol>\n<li><p>There might be cases where you actually want to modify the input object,\nbut when you adopt this programming practice you will find that those cases\nare pretty rare. Most things can be refactored to have no side effects!</p></li>\n<li><p>Cloning big objects can be very expensive in terms of performance. Luckily,\nthis isn't a big issue in practice because there are\n<a href=\"https://facebook.github.io/immutable-js/\">great libraries</a> that allow\nthis kind of programming approach to be fast and not as memory intensive as\nit would be for you to manually clone objects and arrays.</p></li>\n</ol>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const addItemToCart = (cart, item) =&gt; {\n cart.push({ item, date: Date.now() });\n};\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">const addItemToCart = (cart, item) =&gt; {\n return [...cart, { item, date: Date.now() }];\n};\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"dontwritetoglobalfunctions\">Don't write to global functions</h3>\n<p>Polluting globals is a bad practice in JavaScript because you could clash with another\nlibrary and the user of your API would be none-the-wiser until they get an\nexception in production. Let's think about an example: what if you wanted to\nextend JavaScript's native Array method to have a <code>diff</code> method that could\nshow the difference between two arrays? You could write your new function\nto the <code>Array.prototype</code>, but it could clash with another library that tried\nto do the same thing. What if that other library was just using <code>diff</code> to find\nthe difference between the first and last elements of an array? This is why it\nwould be much better to just use ES2015/ES6 classes and simply extend the <code>Array</code> global.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">Array.prototype.diff = function diff(comparisonArray) {\n const hash = new Set(comparisonArray);\n return this.filter(elem =&gt; !hash.has(elem));\n};\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class SuperArray extends Array {\n diff(comparisonArray) {\n const hash = new Set(comparisonArray);\n return this.filter(elem =&gt; !hash.has(elem));\n }\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"favorfunctionalprogrammingoverimperativeprogramming\">Favor functional programming over imperative programming</h3>\n<p>JavaScript isn't a functional language in the way that Haskell is, but it has\na functional flavor to it. Functional languages can be cleaner and easier to test.\nFavor this style of programming when you can.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const programmerOutput = [\n {\n name: \"Uncle Bobby\",\n linesOfCode: 500\n },\n {\n name: \"Suzie Q\",\n linesOfCode: 1500\n },\n {\n name: \"Jimmy Gosling\",\n linesOfCode: 150\n },\n {\n name: \"Gracie Hopper\",\n linesOfCode: 1000\n }\n];\n\nlet totalOutput = 0;\n\nfor (let i = 0; i &lt; programmerOutput.length; i++) {\n totalOutput += programmerOutput[i].linesOfCode;\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">const programmerOutput = [\n {\n name: \"Uncle Bobby\",\n linesOfCode: 500\n },\n {\n name: \"Suzie Q\",\n linesOfCode: 1500\n },\n {\n name: \"Jimmy Gosling\",\n linesOfCode: 150\n },\n {\n name: \"Gracie Hopper\",\n linesOfCode: 1000\n }\n];\n\nconst totalOutput = programmerOutput.reduce(\n (totalLines, output) =&gt; totalLines + output.linesOfCode,\n 0\n);\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"encapsulateconditionals\">Encapsulate conditionals</h3>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">if (fsm.state === \"fetching\" &amp;&amp; isEmpty(listNode)) {\n // ...\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function shouldShowSpinner(fsm, listNode) {\n return fsm.state === \"fetching\" &amp;&amp; isEmpty(listNode);\n}\n\nif (shouldShowSpinner(fsmInstance, listNodeInstance)) {\n // ...\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"avoidnegativeconditionals\">Avoid negative conditionals</h3>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function isDOMNodeNotPresent(node) {\n // ...\n}\n\nif (!isDOMNodeNotPresent(node)) {\n // ...\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function isDOMNodePresent(node) {\n // ...\n}\n\nif (isDOMNodePresent(node)) {\n // ...\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"avoidconditionals\">Avoid conditionals</h3>\n<p>This seems like an impossible task. Upon first hearing this, most people say,\n\"how am I supposed to do anything without an <code>if</code> statement?\" The answer is that\nyou can use polymorphism to achieve the same task in many cases. The second\nquestion is usually, \"well that's great but why would I want to do that?\" The\nanswer is a previous clean code concept we learned: a function should only do\none thing. When you have classes and functions that have <code>if</code> statements, you\nare telling your user that your function does more than one thing. Remember,\njust do one thing.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class Airplane {\n // ...\n getCruisingAltitude() {\n switch (this.type) {\n case \"777\":\n return this.getMaxAltitude() - this.getPassengerCount();\n case \"Air Force One\":\n return this.getMaxAltitude();\n case \"Cessna\":\n return this.getMaxAltitude() - this.getFuelExpenditure();\n }\n }\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class Airplane {\n // ...\n}\n\nclass Boeing777 extends Airplane {\n // ...\n getCruisingAltitude() {\n return this.getMaxAltitude() - this.getPassengerCount();\n }\n}\n\nclass AirForceOne extends Airplane {\n // ...\n getCruisingAltitude() {\n return this.getMaxAltitude();\n }\n}\n\nclass Cessna extends Airplane {\n // ...\n getCruisingAltitude() {\n return this.getMaxAltitude() - this.getFuelExpenditure();\n }\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"avoidtypecheckingpart1\">Avoid type-checking (part 1)</h3>\n<p>JavaScript is untyped, which means your functions can take any type of argument.\nSometimes you are bitten by this freedom and it becomes tempting to do\ntype-checking in your functions. There are many ways to avoid having to do this.\nThe first thing to consider is consistent APIs.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function travelToTexas(vehicle) {\n if (vehicle instanceof Bicycle) {\n vehicle.pedal(this.currentLocation, new Location(\"texas\"));\n } else if (vehicle instanceof Car) {\n vehicle.drive(this.currentLocation, new Location(\"texas\"));\n }\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function travelToTexas(vehicle) {\n vehicle.move(this.currentLocation, new Location(\"texas\"));\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"avoidtypecheckingpart2\">Avoid type-checking (part 2)</h3>\n<p>If you are working with basic primitive values like strings and integers,\nand you can't use polymorphism but you still feel the need to type-check,\nyou should consider using TypeScript. It is an excellent alternative to normal\nJavaScript, as it provides you with static typing on top of standard JavaScript\nsyntax. The problem with manually type-checking normal JavaScript is that\ndoing it well requires so much extra verbiage that the faux \"type-safety\" you get\ndoesn't make up for the lost readability. Keep your JavaScript clean, write\ngood tests, and have good code reviews. Otherwise, do all of that but with\nTypeScript (which, like I said, is a great alternative!).</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function combine(val1, val2) {\n if (\n (typeof val1 === \"number\" &amp;&amp; typeof val2 === \"number\") ||\n (typeof val1 === \"string\" &amp;&amp; typeof val2 === \"string\")\n ) {\n return val1 + val2;\n }\n\n throw new Error(\"Must be of type String or Number\");\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function combine(val1, val2) {\n return val1 + val2;\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"dontoveroptimize\">Don't over-optimize</h3>\n<p>Modern browsers do a lot of optimization under-the-hood at runtime. A lot of\ntimes, if you are optimizing then you are just wasting your time. <a href=\"https://github.com/petkaantonov/bluebird/wiki/Optimization-killers\">There are good\nresources</a>\nfor seeing where optimization is lacking. Target those in the meantime, until\nthey are fixed if they can be.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">// On old browsers, each iteration with uncached `list.length` would be costly\n// because of `list.length` recomputation. In modern browsers, this is optimized.\nfor (let i = 0, len = list.length; i &lt; len; i++) {\n // ...\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">for (let i = 0; i &lt; list.length; i++) {\n // ...\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"removedeadcode\">Remove dead code</h3>\n<p>Dead code is just as bad as duplicate code. There's no reason to keep it in\nyour codebase. If it's not being called, get rid of it! It will still be safe\nin your version history if you still need it.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function oldRequestModule(url) {\n // ...\n}\n\nfunction newRequestModule(url) {\n // ...\n}\n\nconst req = newRequestModule;\ninventoryTracker(\"apples\", req, \"www.inventory-awesome.io\");\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function newRequestModule(url) {\n // ...\n}\n\nconst req = newRequestModule;\ninventoryTracker(\"apples\", req, \"www.inventory-awesome.io\");\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"objectsanddatastructures\"><strong>Objects and Data Structures</strong></h2>\n<h3 id=\"usegettersandsetters\">Use getters and setters</h3>\n<p>Using getters and setters to access data on objects could be better than simply\nlooking for a property on an object. \"Why?\" you might ask. Well, here's an\nunorganized list of reasons why:</p>\n<ul>\n<li>When you want to do more beyond getting an object property, you don't have\nto look up and change every accessor in your codebase.</li>\n<li>Makes adding validation simple when doing a <code>set</code>.</li>\n<li>Encapsulates the internal representation.</li>\n<li>Easy to add logging and error handling when getting and setting.</li>\n<li>You can lazy load your object's properties, let's say getting it from a\nserver.</li>\n</ul>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function makeBankAccount() {\n // ...\n\n return {\n balance: 0\n // ...\n };\n}\n\nconst account = makeBankAccount();\naccount.balance = 100;\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function makeBankAccount() {\n // this one is private\n let balance = 0;\n\n // a \"getter\", made public via the returned object below\n function getBalance() {\n return balance;\n }\n\n // a \"setter\", made public via the returned object below\n function setBalance(amount) {\n // ... validate before updating the balance\n balance = amount;\n }\n\n return {\n // ...\n getBalance,\n setBalance\n };\n}\n\nconst account = makeBankAccount();\naccount.setBalance(100);\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"makeobjectshaveprivatemembers\">Make objects have private members</h3>\n<p>This can be accomplished through closures (for ES5 and below).</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const Employee = function(name) {\n this.name = name;\n};\n\nEmployee.prototype.getName = function getName() {\n return this.name;\n};\n\nconst employee = new Employee(\"John Doe\");\nconsole.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe\ndelete employee.name;\nconsole.log(`Employee name: ${employee.getName()}`); // Employee name: undefined\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function makeEmployee(name) {\n return {\n getName() {\n return name;\n }\n };\n}\n\nconst employee = makeEmployee(\"John Doe\");\nconsole.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe\ndelete employee.name;\nconsole.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"classes\"><strong>Classes</strong></h2>\n<h3 id=\"preferes2015es6classesoveres5plainfunctions\">Prefer ES2015/ES6 classes over ES5 plain functions</h3>\n<p>It's very difficult to get readable class inheritance, construction, and method\ndefinitions for classical ES5 classes. If you need inheritance (and be aware\nthat you might not), then prefer ES2015/ES6 classes. However, prefer small functions over\nclasses until you find yourself needing larger and more complex objects.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const Animal = function(age) {\n if (!(this instanceof Animal)) {\n throw new Error(\"Instantiate Animal with `new`\");\n }\n\n this.age = age;\n};\n\nAnimal.prototype.move = function move() {};\n\nconst Mammal = function(age, furColor) {\n if (!(this instanceof Mammal)) {\n throw new Error(\"Instantiate Mammal with `new`\");\n }\n\n Animal.call(this, age);\n this.furColor = furColor;\n};\n\nMammal.prototype = Object.create(Animal.prototype);\nMammal.prototype.constructor = Mammal;\nMammal.prototype.liveBirth = function liveBirth() {};\n\nconst Human = function(age, furColor, languageSpoken) {\n if (!(this instanceof Human)) {\n throw new Error(\"Instantiate Human with `new`\");\n }\n\n Mammal.call(this, age, furColor);\n this.languageSpoken = languageSpoken;\n};\n\nHuman.prototype = Object.create(Mammal.prototype);\nHuman.prototype.constructor = Human;\nHuman.prototype.speak = function speak() {};\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class Animal {\n constructor(age) {\n this.age = age;\n }\n\n move() {\n /* ... */\n }\n}\n\nclass Mammal extends Animal {\n constructor(age, furColor) {\n super(age);\n this.furColor = furColor;\n }\n\n liveBirth() {\n /* ... */\n }\n}\n\nclass Human extends Mammal {\n constructor(age, furColor, languageSpoken) {\n super(age, furColor);\n this.languageSpoken = languageSpoken;\n }\n\n speak() {\n /* ... */\n }\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"usemethodchaining\">Use method chaining</h3>\n<p>This pattern is very useful in JavaScript and you see it in many libraries such\nas jQuery and Lodash. It allows your code to be expressive, and less verbose.\nFor that reason, I say, use method chaining and take a look at how clean your code\nwill be. In your class functions, simply return <code>this</code> at the end of every function,\nand you can chain further class methods onto it.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class Car {\n constructor(make, model, color) {\n this.make = make;\n this.model = model;\n this.color = color;\n }\n\n setMake(make) {\n this.make = make;\n }\n\n setModel(model) {\n this.model = model;\n }\n\n setColor(color) {\n this.color = color;\n }\n\n save() {\n console.log(this.make, this.model, this.color);\n }\n}\n\nconst car = new Car(\"Ford\", \"F-150\", \"red\");\ncar.setColor(\"pink\");\ncar.save();\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class Car {\n constructor(make, model, color) {\n this.make = make;\n this.model = model;\n this.color = color;\n }\n\n setMake(make) {\n this.make = make;\n // NOTE: Returning this for chaining\n return this;\n }\n\n setModel(model) {\n this.model = model;\n // NOTE: Returning this for chaining\n return this;\n }\n\n setColor(color) {\n this.color = color;\n // NOTE: Returning this for chaining\n return this;\n }\n\n save() {\n console.log(this.make, this.model, this.color);\n // NOTE: Returning this for chaining\n return this;\n }\n}\n\nconst car = new Car(\"Ford\", \"F-150\", \"red\").setColor(\"pink\").save();\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"prefercompositionoverinheritance\">Prefer composition over inheritance</h3>\n<p>As stated famously in <a href=\"https://en.wikipedia.org/wiki/Design_Patterns\"><em>Design Patterns</em></a> by the Gang of Four,\nyou should prefer composition over inheritance where you can. There are lots of\ngood reasons to use inheritance and lots of good reasons to use composition.\nThe main point for this maxim is that if your mind instinctively goes for\ninheritance, try to think if composition could model your problem better. In some\ncases it can.</p>\n<p>You might be wondering then, \"when should I use inheritance?\" It\ndepends on your problem at hand, but this is a decent list of when inheritance\nmakes more sense than composition:</p>\n<ol>\n<li>Your inheritance represents an \"is-a\" relationship and not a \"has-a\"\nrelationship (Human-&gt;Animal vs. User-&gt;UserDetails).</li>\n<li>You can reuse code from the base classes (Humans can move like all animals).</li>\n<li>You want to make global changes to derived classes by changing a base class.\n(Change the caloric expenditure of all animals when they move).</li>\n</ol>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class Employee {\n constructor(name, email) {\n this.name = name;\n this.email = email;\n }\n\n // ...\n}\n\n// Bad because Employees \"have\" tax data. EmployeeTaxData is not a type of Employee\nclass EmployeeTaxData extends Employee {\n constructor(ssn, salary) {\n super();\n this.ssn = ssn;\n this.salary = salary;\n }\n\n // ...\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class EmployeeTaxData {\n constructor(ssn, salary) {\n this.ssn = ssn;\n this.salary = salary;\n }\n\n // ...\n}\n\nclass Employee {\n constructor(name, email) {\n this.name = name;\n this.email = email;\n }\n\n setTaxData(ssn, salary) {\n this.taxData = new EmployeeTaxData(ssn, salary);\n }\n // ...\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"solid\"><strong>SOLID</strong></h2>\n<h3 id=\"singleresponsibilityprinciplesrp\">Single Responsibility Principle (SRP)</h3>\n<p>As stated in Clean Code, \"There should never be more than one reason for a class\nto change\". It's tempting to jam-pack a class with a lot of functionality, like\nwhen you can only take one suitcase on your flight. The issue with this is\nthat your class won't be conceptually cohesive and it will give it many reasons\nto change. Minimizing the amount of times you need to change a class is important.\nIt's important because if too much functionality is in one class and you modify\na piece of it, it can be difficult to understand how that will affect other\ndependent modules in your codebase.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class UserSettings {\n constructor(user) {\n this.user = user;\n }\n\n changeSettings(settings) {\n if (this.verifyCredentials()) {\n // ...\n }\n }\n\n verifyCredentials() {\n // ...\n }\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class UserAuth {\n constructor(user) {\n this.user = user;\n }\n\n verifyCredentials() {\n // ...\n }\n}\n\nclass UserSettings {\n constructor(user) {\n this.user = user;\n this.auth = new UserAuth(user);\n }\n\n changeSettings(settings) {\n if (this.auth.verifyCredentials()) {\n // ...\n }\n }\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"openclosedprincipleocp\">Open/Closed Principle (OCP)</h3>\n<p>As stated by Bertrand Meyer, \"software entities (classes, modules, functions,\netc.) should be open for extension, but closed for modification.\" What does that\nmean though? This principle basically states that you should allow users to\nadd new functionalities without changing existing code.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class AjaxAdapter extends Adapter {\n constructor() {\n super();\n this.name = \"ajaxAdapter\";\n }\n}\n\nclass NodeAdapter extends Adapter {\n constructor() {\n super();\n this.name = \"nodeAdapter\";\n }\n}\n\nclass HttpRequester {\n constructor(adapter) {\n this.adapter = adapter;\n }\n\n fetch(url) {\n if (this.adapter.name === \"ajaxAdapter\") {\n return makeAjaxCall(url).then(response =&gt; {\n // transform response and return\n });\n } else if (this.adapter.name === \"nodeAdapter\") {\n return makeHttpCall(url).then(response =&gt; {\n // transform response and return\n });\n }\n }\n}\n\nfunction makeAjaxCall(url) {\n // request and return promise\n}\n\nfunction makeHttpCall(url) {\n // request and return promise\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class AjaxAdapter extends Adapter {\n constructor() {\n super();\n this.name = \"ajaxAdapter\";\n }\n\n request(url) {\n // request and return promise\n }\n}\n\nclass NodeAdapter extends Adapter {\n constructor() {\n super();\n this.name = \"nodeAdapter\";\n }\n\n request(url) {\n // request and return promise\n }\n}\n\nclass HttpRequester {\n constructor(adapter) {\n this.adapter = adapter;\n }\n\n fetch(url) {\n return this.adapter.request(url).then(response =&gt; {\n // transform response and return\n });\n }\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"liskovsubstitutionprinciplelsp\">Liskov Substitution Principle (LSP)</h3>\n<p>This is a scary term for a very simple concept. It's formally defined as \"If S\nis a subtype of T, then objects of type T may be replaced with objects of type S\n(i.e., objects of type S may substitute objects of type T) without altering any\nof the desirable properties of that program (correctness, task performed,\netc.).\" That's an even scarier definition.</p>\n<p>The best explanation for this is if you have a parent class and a child class,\nthen the base class and child class can be used interchangeably without getting\nincorrect results. This might still be confusing, so let's take a look at the\nclassic Square-Rectangle example. Mathematically, a square is a rectangle, but\nif you model it using the \"is-a\" relationship via inheritance, you quickly\nget into trouble.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class Rectangle {\n constructor() {\n this.width = 0;\n this.height = 0;\n }\n\n setColor(color) {\n // ...\n }\n\n render(area) {\n // ...\n }\n\n setWidth(width) {\n this.width = width;\n }\n\n setHeight(height) {\n this.height = height;\n }\n\n getArea() {\n return this.width * this.height;\n }\n}\n\nclass Square extends Rectangle {\n setWidth(width) {\n this.width = width;\n this.height = width;\n }\n\n setHeight(height) {\n this.width = height;\n this.height = height;\n }\n}\n\nfunction renderLargeRectangles(rectangles) {\n rectangles.forEach(rectangle =&gt; {\n rectangle.setWidth(4);\n rectangle.setHeight(5);\n const area = rectangle.getArea(); // BAD: Returns 25 for Square. Should be 20.\n rectangle.render(area);\n });\n}\n\nconst rectangles = [new Rectangle(), new Rectangle(), new Square()];\nrenderLargeRectangles(rectangles);\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class Shape {\n setColor(color) {\n // ...\n }\n\n render(area) {\n // ...\n }\n}\n\nclass Rectangle extends Shape {\n constructor(width, height) {\n super();\n this.width = width;\n this.height = height;\n }\n\n getArea() {\n return this.width * this.height;\n }\n}\n\nclass Square extends Shape {\n constructor(length) {\n super();\n this.length = length;\n }\n\n getArea() {\n return this.length * this.length;\n }\n}\n\nfunction renderLargeShapes(shapes) {\n shapes.forEach(shape =&gt; {\n const area = shape.getArea();\n shape.render(area);\n });\n}\n\nconst shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];\nrenderLargeShapes(shapes);\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"interfacesegregationprincipleisp\">Interface Segregation Principle (ISP)</h3>\n<p>JavaScript doesn't have interfaces so this principle doesn't apply as strictly\nas others. However, it's important and relevant even with JavaScript's lack of\ntype system.</p>\n<p>ISP states that \"Clients should not be forced to depend upon interfaces that\nthey do not use.\" Interfaces are implicit contracts in JavaScript because of\nduck typing.</p>\n<p>A good example to look at that demonstrates this principle in JavaScript is for\nclasses that require large settings objects. Not requiring clients to setup\nhuge amounts of options is beneficial, because most of the time they won't need\nall of the settings. Making them optional helps prevent having a\n\"fat interface\".</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class DOMTraverser {\n constructor(settings) {\n this.settings = settings;\n this.setup();\n }\n\n setup() {\n this.rootNode = this.settings.rootNode;\n this.settings.animationModule.setup();\n }\n\n traverse() {\n // ...\n }\n}\n\nconst $ = new DOMTraverser({\n rootNode: document.getElementsByTagName(\"body\"),\n animationModule() {} // Most of the time, we won't need to animate when traversing.\n // ...\n});\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class DOMTraverser {\n constructor(settings) {\n this.settings = settings;\n this.options = settings.options;\n this.setup();\n }\n\n setup() {\n this.rootNode = this.settings.rootNode;\n this.setupOptions();\n }\n\n setupOptions() {\n if (this.options.animationModule) {\n // ...\n }\n }\n\n traverse() {\n // ...\n }\n}\n\nconst $ = new DOMTraverser({\n rootNode: document.getElementsByTagName(\"body\"),\n options: {\n animationModule() {}\n }\n});\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"dependencyinversionprincipledip\">Dependency Inversion Principle (DIP)</h3>\n<p>This principle states two essential things:</p>\n<ol>\n<li>High-level modules should not depend on low-level modules. Both should\ndepend on abstractions.</li>\n<li>Abstractions should not depend upon details. Details should depend on\nabstractions.</li>\n</ol>\n<p>This can be hard to understand at first, but if you've worked with AngularJS,\nyou've seen an implementation of this principle in the form of Dependency\nInjection (DI). While they are not identical concepts, DIP keeps high-level\nmodules from knowing the details of its low-level modules and setting them up.\nIt can accomplish this through DI. A huge benefit of this is that it reduces\nthe coupling between modules. Coupling is a very bad development pattern because\nit makes your code hard to refactor.</p>\n<p>As stated previously, JavaScript doesn't have interfaces so the abstractions\nthat are depended upon are implicit contracts. That is to say, the methods\nand properties that an object/class exposes to another object/class. In the\nexample below, the implicit contract is that any Request module for an\n<code>InventoryTracker</code> will have a <code>requestItems</code> method.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class InventoryRequester {\n constructor() {\n this.REQ_METHODS = [\"HTTP\"];\n }\n\n requestItem(item) {\n // ...\n }\n}\n\nclass InventoryTracker {\n constructor(items) {\n this.items = items;\n\n // BAD: We have created a dependency on a specific request implementation.\n // We should just have requestItems depend on a request method: `request`\n this.requester = new InventoryRequester();\n }\n\n requestItems() {\n this.items.forEach(item =&gt; {\n this.requester.requestItem(item);\n });\n }\n}\n\nconst inventoryTracker = new InventoryTracker([\"apples\", \"bananas\"]);\ninventoryTracker.requestItems();\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class InventoryTracker {\n constructor(items, requester) {\n this.items = items;\n this.requester = requester;\n }\n\n requestItems() {\n this.items.forEach(item =&gt; {\n this.requester.requestItem(item);\n });\n }\n}\n\nclass InventoryRequesterV1 {\n constructor() {\n this.REQ_METHODS = [\"HTTP\"];\n }\n\n requestItem(item) {\n // ...\n }\n}\n\nclass InventoryRequesterV2 {\n constructor() {\n this.REQ_METHODS = [\"WS\"];\n }\n\n requestItem(item) {\n // ...\n }\n}\n\n// By constructing our dependencies externally and injecting them, we can easily\n// substitute our request module for a fancy new one that uses WebSockets.\nconst inventoryTracker = new InventoryTracker(\n [\"apples\", \"bananas\"],\n new InventoryRequesterV2()\n);\ninventoryTracker.requestItems();\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"testing\"><strong>Testing</strong></h2>\n<p>Testing is more important than shipping. If you have no tests or an\ninadequate amount, then every time you ship code you won't be sure that you\ndidn't break anything. Deciding on what constitutes an adequate amount is up\nto your team, but having 100% coverage (all statements and branches) is how\nyou achieve very high confidence and developer peace of mind. This means that\nin addition to having a great testing framework, you also need to use a\n<a href=\"https://gotwarlost.github.io/istanbul/\">good coverage tool</a>.</p>\n<p>There's no excuse to not write tests. There are <a href=\"https://jstherightway.org/#testing-tools\">plenty of good JS test frameworks</a>, so find one that your team prefers.\nWhen you find one that works for your team, then aim to always write tests\nfor every new feature/module you introduce. If your preferred method is\nTest Driven Development (TDD), that is great, but the main point is to just\nmake sure you are reaching your coverage goals before launching any feature,\nor refactoring an existing one.</p>\n<h3 id=\"singleconceptpertest\">Single concept per test</h3>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">import assert from \"assert\";\n\ndescribe(\"MomentJS\", () =&gt; {\n it(\"handles date boundaries\", () =&gt; {\n let date;\n\n date = new MomentJS(\"1/1/2015\");\n date.addDays(30);\n assert.equal(\"1/31/2015\", date);\n\n date = new MomentJS(\"2/1/2016\");\n date.addDays(28);\n assert.equal(\"02/29/2016\", date);\n\n date = new MomentJS(\"2/1/2015\");\n date.addDays(28);\n assert.equal(\"03/01/2015\", date);\n });\n});\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">import assert from \"assert\";\n\ndescribe(\"MomentJS\", () =&gt; {\n it(\"handles 30-day months\", () =&gt; {\n const date = new MomentJS(\"1/1/2015\");\n date.addDays(30);\n assert.equal(\"1/31/2015\", date);\n });\n\n it(\"handles leap year\", () =&gt; {\n const date = new MomentJS(\"2/1/2016\");\n date.addDays(28);\n assert.equal(\"02/29/2016\", date);\n });\n\n it(\"handles non-leap year\", () =&gt; {\n const date = new MomentJS(\"2/1/2015\");\n date.addDays(28);\n assert.equal(\"03/01/2015\", date);\n });\n});\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"concurrency\"><strong>Concurrency</strong></h2>\n<h3 id=\"usepromisesnotcallbacks\">Use Promises, not callbacks</h3>\n<p>Callbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6,\nPromises are a built-in global type. Use them!</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">import { get } from \"request\";\nimport { writeFile } from \"fs\";\n\nget(\n \"https://en.wikipedia.org/wiki/Robert_Cecil_Martin\",\n (requestErr, response, body) =&gt; {\n if (requestErr) {\n console.error(requestErr);\n } else {\n writeFile(\"article.html\", body, writeErr =&gt; {\n if (writeErr) {\n console.error(writeErr);\n } else {\n console.log(\"File written\");\n }\n });\n }\n }\n);\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">import { get } from \"request-promise\";\nimport { writeFile } from \"fs-extra\";\n\nget(\"https://en.wikipedia.org/wiki/Robert_Cecil_Martin\")\n .then(body =&gt; {\n return writeFile(\"article.html\", body);\n })\n .then(() =&gt; {\n console.log(\"File written\");\n })\n .catch(err =&gt; {\n console.error(err);\n });\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"asyncawaitareevencleanerthanpromises\">Async/Await are even cleaner than Promises</h3>\n<p>Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await\nwhich offer an even cleaner solution. All you need is a function that is prefixed\nin an <code>async</code> keyword, and then you can write your logic imperatively without\na <code>then</code> chain of functions. Use this if you can take advantage of ES2017/ES8 features\ntoday!</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">import { get } from \"request-promise\";\nimport { writeFile } from \"fs-extra\";\n\nget(\"https://en.wikipedia.org/wiki/Robert_Cecil_Martin\")\n .then(body =&gt; {\n return writeFile(\"article.html\", body);\n })\n .then(() =&gt; {\n console.log(\"File written\");\n })\n .catch(err =&gt; {\n console.error(err);\n });\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">import { get } from \"request-promise\";\nimport { writeFile } from \"fs-extra\";\n\nasync function getCleanCodeArticle() {\n try {\n const body = await get(\n \"https://en.wikipedia.org/wiki/Robert_Cecil_Martin\"\n );\n await writeFile(\"article.html\", body);\n console.log(\"File written\");\n } catch (err) {\n console.error(err);\n }\n}\n\ngetCleanCodeArticle()\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"errorhandling\"><strong>Error Handling</strong></h2>\n<p>Thrown errors are a good thing! They mean the runtime has successfully\nidentified when something in your program has gone wrong and it's letting\nyou know by stopping function execution on the current stack, killing the\nprocess (in Node), and notifying you in the console with a stack trace.</p>\n<h3 id=\"dontignorecaughterrors\">Don't ignore caught errors</h3>\n<p>Doing nothing with a caught error doesn't give you the ability to ever fix\nor react to said error. Logging the error to the console (<code>console.log</code>)\nisn't much better as often times it can get lost in a sea of things printed\nto the console. If you wrap any bit of code in a <code>try/catch</code> it means you\nthink an error may occur there and therefore you should have a plan,\nor create a code path, for when it occurs.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">try {\n functionThatMightThrow();\n} catch (error) {\n console.log(error);\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">try {\n functionThatMightThrow();\n} catch (error) {\n // One option (more noisy than console.log):\n console.error(error);\n // Another option:\n notifyUserOfError(error);\n // Another option:\n reportErrorToService(error);\n // OR do all three!\n}\n</code></pre>\n<h3 id=\"dontignorerejectedpromises\">Don't ignore rejected promises</h3>\n<p>For the same reason you shouldn't ignore caught errors\nfrom <code>try/catch</code>.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">getdata()\n .then(data =&gt; {\n functionThatMightThrow(data);\n })\n .catch(error =&gt; {\n console.log(error);\n });\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">getdata()\n .then(data =&gt; {\n functionThatMightThrow(data);\n })\n .catch(error =&gt; {\n // One option (more noisy than console.log):\n console.error(error);\n // Another option:\n notifyUserOfError(error);\n // Another option:\n reportErrorToService(error);\n // OR do all three!\n });\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"formatting\"><strong>Formatting</strong></h2>\n<p>Formatting is subjective. Like many rules herein, there is no hard and fast\nrule that you must follow. The main point is DO NOT ARGUE over formatting.\nThere are <a href=\"https://standardjs.com/rules.html\">tons of tools</a> to automate this.\nUse one! It's a waste of time and money for engineers to argue over formatting.</p>\n<p>For things that don't fall under the purview of automatic formatting\n(indentation, tabs vs. spaces, double vs. single quotes, etc.) look here\nfor some guidance.</p>\n<h3 id=\"useconsistentcapitalization\">Use consistent capitalization</h3>\n<p>JavaScript is untyped, so capitalization tells you a lot about your variables,\nfunctions, etc. These rules are subjective, so your team can choose whatever\nthey want. The point is, no matter what you all choose, just be consistent.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">const DAYS_IN_WEEK = 7;\nconst daysInMonth = 30;\n\nconst songs = [\"Back In Black\", \"Stairway to Heaven\", \"Hey Jude\"];\nconst Artists = [\"ACDC\", \"Led Zeppelin\", \"The Beatles\"];\n\nfunction eraseDatabase() {}\nfunction restore_database() {}\n\nclass animal {}\nclass Alpaca {}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">const DAYS_IN_WEEK = 7;\nconst DAYS_IN_MONTH = 30;\n\nconst SONGS = [\"Back In Black\", \"Stairway to Heaven\", \"Hey Jude\"];\nconst ARTISTS = [\"ACDC\", \"Led Zeppelin\", \"The Beatles\"];\n\nfunction eraseDatabase() {}\nfunction restoreDatabase() {}\n\nclass Animal {}\nclass Alpaca {}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"functioncallersandcalleesshouldbeclose\">Function callers and callees should be close</h3>\n<p>If a function calls another, keep those functions vertically close in the source\nfile. Ideally, keep the caller right above the callee. We tend to read code from\ntop-to-bottom, like a newspaper. Because of this, make your code read that way.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">class PerformanceReview {\n constructor(employee) {\n this.employee = employee;\n }\n\n lookupPeers() {\n return db.lookup(this.employee, \"peers\");\n }\n\n lookupManager() {\n return db.lookup(this.employee, \"manager\");\n }\n\n getPeerReviews() {\n const peers = this.lookupPeers();\n // ...\n }\n\n perfReview() {\n this.getPeerReviews();\n this.getManagerReview();\n this.getSelfReview();\n }\n\n getManagerReview() {\n const manager = this.lookupManager();\n }\n\n getSelfReview() {\n // ...\n }\n}\n\nconst review = new PerformanceReview(employee);\nreview.perfReview();\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">class PerformanceReview {\n constructor(employee) {\n this.employee = employee;\n }\n\n perfReview() {\n this.getPeerReviews();\n this.getManagerReview();\n this.getSelfReview();\n }\n\n getPeerReviews() {\n const peers = this.lookupPeers();\n // ...\n }\n\n lookupPeers() {\n return db.lookup(this.employee, \"peers\");\n }\n\n getManagerReview() {\n const manager = this.lookupManager();\n }\n\n lookupManager() {\n return db.lookup(this.employee, \"manager\");\n }\n\n getSelfReview() {\n // ...\n }\n}\n\nconst review = new PerformanceReview(employee);\nreview.perfReview();\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"comments\"><strong>Comments</strong></h2>\n<h3 id=\"onlycommentthingsthathavebusinesslogiccomplexity\">Only comment things that have business logic complexity.</h3>\n<p>Comments are an apology, not a requirement. Good code <em>mostly</em> documents itself.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">function hashIt(data) {\n // The hash\n let hash = 0;\n\n // Length of string\n const length = data.length;\n\n // Loop through every character in data\n for (let i = 0; i &lt; length; i++) {\n // Get character code.\n const char = data.charCodeAt(i);\n // Make the hash\n hash = (hash &lt;&lt; 5) - hash + char;\n // Convert to 32-bit integer\n hash &amp;= hash;\n }\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function hashIt(data) {\n let hash = 0;\n const length = data.length;\n\n for (let i = 0; i &lt; length; i++) {\n const char = data.charCodeAt(i);\n hash = (hash &lt;&lt; 5) - hash + char;\n\n // Convert to 32-bit integer\n hash &amp;= hash;\n }\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"dontleavecommentedoutcodeinyourcodebase\">Don't leave commented out code in your codebase</h3>\n<p>Version control exists for a reason. Leave old code in your history.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">doStuff();\n// doOtherStuff();\n// doSomeMoreStuff();\n// doSoMuchStuff();\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">doStuff();\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"donthavejournalcomments\">Don't have journal comments</h3>\n<p>Remember, use version control! There's no need for dead code, commented code,\nand especially journal comments. Use <code>git log</code> to get history!</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">/**\n * 2016-12-20: Removed monads, didn't understand them (RM)\n * 2016-10-01: Improved using special monads (JP)\n * 2016-02-03: Removed type-checking (LI)\n * 2015-03-14: Added combine with type-checking (JR)\n */\nfunction combine(a, b) {\n return a + b;\n}\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">function combine(a, b) {\n return a + b;\n}\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h3 id=\"avoidpositionalmarkers\">Avoid positional markers</h3>\n<p>They usually just add noise. Let the functions and variable names along with the\nproper indentation and formatting give the visual structure to your code.</p>\n<p><strong>Bad:</strong></p>\n<pre><code class=\"javascript language-javascript\">////////////////////////////////////////////////////////////////////////////////\n// Scope Model Instantiation\n////////////////////////////////////////////////////////////////////////////////\n$scope.model = {\n menu: \"foo\",\n nav: \"bar\"\n};\n\n////////////////////////////////////////////////////////////////////////////////\n// Action setup\n////////////////////////////////////////////////////////////////////////////////\nconst actions = function() {\n // ...\n};\n</code></pre>\n<p><strong>Good:</strong></p>\n<pre><code class=\"javascript language-javascript\">$scope.model = {\n menu: \"foo\",\n nav: \"bar\"\n};\n\nconst actions = function() {\n // ...\n};\n</code></pre>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>\n<h2 id=\"translation\">Translation</h2>\n<p>This is also available in other languages:</p>\n<ul>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Armenia.png\" alt=\"am\" /> <strong>Armenian</strong>: <a href=\"https://github.com/hanumanum/clean-code-javascript\">hanumanum/clean-code-javascript/</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Bangladesh.png\" alt=\"bd\" /> <strong>Bangla(বাংলা)</strong>: <a href=\"https://github.com/InsomniacSabbir/clean-code-javascript/\">InsomniacSabbir/clean-code-javascript/</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Brazil.png\" alt=\"br\" /> <strong>Brazilian Portuguese</strong>: <a href=\"https://github.com/fesnt/clean-code-javascript\">fesnt/clean-code-javascript</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/China.png\" alt=\"cn\" /> <strong>Simplified Chinese</strong>:</li>\n<li><a href=\"https://github.com/alivebao/clean-code-js\">alivebao/clean-code-js</a></li>\n<li><a href=\"https://github.com/beginor/clean-code-javascript\">beginor/clean-code-javascript</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Taiwan.png\" alt=\"tw\" /> <strong>Traditional Chinese</strong>: <a href=\"https://github.com/AllJointTW/clean-code-javascript\">AllJointTW/clean-code-javascript</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/France.png\" alt=\"fr\" /> <strong>French</strong>: <a href=\"https://github.com/GavBaros/clean-code-javascript-fr\">GavBaros/clean-code-javascript-fr</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Germany.png\" alt=\"de\" /> <strong>German</strong>: <a href=\"https://github.com/marcbruederlin/clean-code-javascript\">marcbruederlin/clean-code-javascript</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Indonesia.png\" alt=\"id\" /> <strong>Indonesia</strong>: <a href=\"https://github.com/andirkh/clean-code-javascript/\">andirkh/clean-code-javascript/</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Italy.png\" alt=\"it\" /> <strong>Italian</strong>: <a href=\"https://github.com/frappacchio/clean-code-javascript/\">frappacchio/clean-code-javascript/</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Japan.png\" alt=\"ja\" /> <strong>Japanese</strong>: <a href=\"https://github.com/mitsuruog/clean-code-javascript/\">mitsuruog/clean-code-javascript/</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/South-Korea.png\" alt=\"kr\" /> <strong>Korean</strong>: <a href=\"https://github.com/qkraudghgh/clean-code-javascript-ko\">qkraudghgh/clean-code-javascript-ko</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Poland.png\" alt=\"pl\" /> <strong>Polish</strong>: <a href=\"https://github.com/greg-dev/clean-code-javascript-pl\">greg-dev/clean-code-javascript-pl</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Russia.png\" alt=\"ru\" /> <strong>Russian</strong>:</li>\n<li><a href=\"https://github.com/BoryaMogila/clean-code-javascript-ru/\">BoryaMogila/clean-code-javascript-ru/</a></li>\n<li><a href=\"https://github.com/maksugr/clean-code-javascript\">maksugr/clean-code-javascript</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Spain.png\" alt=\"es\" /> <strong>Spanish</strong>: <a href=\"https://github.com/tureey/clean-code-javascript\">tureey/clean-code-javascript</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Uruguay.png\" alt=\"es\" /> <strong>Spanish</strong>: <a href=\"https://github.com/andersontr15/clean-code-javascript-es\">andersontr15/clean-code-javascript</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Turkey.png\" alt=\"tr\" /> <strong>Turkish</strong>: <a href=\"https://github.com/bsonmez/clean-code-javascript/tree/turkish-translation\">bsonmez/clean-code-javascript</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Ukraine.png\" alt=\"ua\" /> <strong>Ukrainian</strong>: <a href=\"https://github.com/mindfr1k/clean-code-javascript-ua\">mindfr1k/clean-code-javascript-ua</a></li>\n<li><img src=\"https://raw.githubusercontent.com/gosquared/flags/master/flags/flags/shiny/24/Vietnam.png\" alt=\"vi\" /> <strong>Vietnamese</strong>: <a href=\"https://github.com/hienvd/clean-code-javascript/\">hienvd/clean-code-javascript/</a></li>\n</ul>\n<p><strong><a href=\"#table-of-contents\">⬆ back to top</a></strong></p>"
},
{
"common": {
"repoName": "react-fundamentals",
"created_at": "Jun 1, 2019",
"user": {
"username": "kentcdodds",
"profile_image_url": "https://avatars0.githubusercontent.com/u/1500684?v=4"
},
"branch": "main"
},
"htmlValue": "<h1 id=\"introtorawreactapis\">Intro to raw React APIs</h1>\n<h2 id=\"background\">Background</h2>\n<p>React is the most widely used frontend framework in the world and it's using the\nsame APIs that you're using when it creates DOM nodes.</p>\n<blockquote>\n <p>In fact,\n <a href=\"https://github.com/facebook/react/blob/48907797294340b6d5d8fecfbcf97edf0691888d/packages/react-dom/src/client/ReactDOMComponent.js#L416\">here's where that happens in the React source code</a>\n at the time of this writing.</p>\n</blockquote>\n<p>React abstracts away the imperative browser API from you to give you a much more\ndeclarative API to work with.</p>\n<blockquote>\n <p>Learn more about the difference between those two concepts here:\n <a href=\"https://tylermcginnis.com/imperative-vs-declarative-programming/\">Imperative vs Declarative Programming</a></p>\n</blockquote>\n<p>One important thing to know about React is that it supports multiple platforms\n(for example, native and web). Each of these platforms has its own code\nnecessary for interacting with that platform, and then there's shared code\nbetween the platforms.</p>\n<p>With that in mind, you need two JavaScript files to write React applications for\nthe web:</p>\n<ul>\n<li>React: responsible for creating React elements (kinda like\n<code>document.createElement()</code>)</li>\n<li>ReactDOM: responsible for rendering React elements to the DOM (kinda like\n<code>rootElement.append()</code>)</li>\n</ul>\n<h2 id=\"exercise\">Exercise</h2>\n<p>Production deploys:</p>\n<ul>\n<li><a href=\"http://react-fundamentals.netlify.app/isolated/exercise/02.html\">Exercise</a></li>\n<li><a href=\"http://react-fundamentals.netlify.app/isolated/final/02.html\">Final</a></li>\n</ul>\n<p>Let's convert this to use React! But don't worry, we won't be doing any JSX just\nyet… You're going to use raw React APIs here.</p>\n<p>In modern applications you'll get React and React DOM files from a \"package\nregistry\" like <a href=\"https://npmjs.com\">npm</a> (<a href=\"https://npm.im/react\">react</a> and\n<a href=\"https://npm.im/react-dom\">react-dom</a>). But for these first exercises, we'll use\nthe script files which are available on <a href=\"https://unpkg.com\">unpkg.com</a> and\nregular script tags so you don't have to bother installing them. So in the\nexercise you'll be required to add script tags for these files.</p>\n<p>Once you include the script tags, you'll have two new global variables to use:\n<code>React</code> and <code>ReactDOM</code>.</p>\n<p>Here's a simple example of the API:</p>\n<pre><code class=\"javascript language-javascript\">const elementProps = {id: 'element-id', children: 'Hello world!'}\nconst elementType = 'h1'\nconst reactElement = React.createElement(elementType, elementProps)\nReactDOM.render(reactElement, rootElement)\n</code></pre>\n<p>Alright! Let's do this!</p>\n<h2 id=\"extracredit\">Extra Credit</h2>\n<h3 id=\"1nestingelements\">1. 💯 nesting elements</h3>\n<p><a href=\"http://react-fundamentals.netlify.app/isolated/final/02.extra-1.html\">Production deploy</a></p>\n<p>See if you can figure out how to write the JavaScript + React code to generate\nthis DOM output:</p>\n<pre><code class=\"html language-html\">&lt;body&gt;\n &lt;div id=\"root\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;span&gt;Hello&lt;/span&gt;\n &lt;span&gt;World&lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n<h2 id=\"elaborationandfeedback\">🦉 Elaboration and Feedback</h2>\n<div>\n<span>After the instruction, if you want to remember what you've just learned, then </span>\n<a rel=\"noopener noreferrer\" target=\"_blank\" href=\"https://ws.kcd.im/?ws=React%20Fundamentals%20%E2%9A%9B&e=02%3A%20Intro%20to%20raw%20React%20APIs&em=\">\n fill out the elaboration and feedback form.\n</a>\n</div>"
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment