clean-code-javascript

Table of Contents

Introduction

Variables

Functions

Objects and Data Structures

Classes

SOLID

Testing

Concurrency

Error Handling

Formatting

Comments

Translation

Introduction

you shout when reading code" class="max-w-full my-2 rounded">

Software engineering principles, from Robert C. Martin's book

_Clean Code_,

adapted for JavaScript. This is not a style guide. It's a guide to producing

readable, reusable, and refactorable software in JavaScript.

Not every principle herein has to be strictly followed, and even fewer will be

universally agreed upon. These are guidelines and nothing more, but they are

ones codified over many years of collective experience by the authors of

_Clean Code_.

Our craft of software engineering is just a bit over 50 years old, and we are

still learning a lot. When software architecture is as old as architecture

itself, maybe then we will have harder rules to follow. For now, let these

guidelines serve as a touchstone by which to assess the quality of the

JavaScript code that you and your team produce.

One more thing: knowing these won't immediately make you a better software

developer, and working with them for many years doesn't mean you won't make

mistakes. Every piece of code starts as a first draft, like wet clay getting

shaped into its final form. Finally, we chisel away the imperfections when

we review it with our peers. Don't beat yourself up for first drafts that need

improvement. Beat up the code instead!

Variables

Use meaningful and pronounceable variable names

Bad:

javascript

1const yyyymmdstr = moment().format("YYYY/MM/DD");

Good:

javascript

1const currentDate = moment().format("YYYY/MM/DD");

⬆ back to top

Use the same vocabulary for the same type of variable

Bad:

javascript

1getUserInfo(); 2getClientData(); 3getCustomerRecord();

Good:

javascript

1getUser();

⬆ back to top

Use searchable names

We will read more code than we will ever write. It's important that the code we

do write is readable and searchable. By _not_ naming variables that end up

being meaningful for understanding our program, we hurt our readers.

Make your names searchable. Tools like

buddy.js and ESLint

can help identify unnamed constants.

Bad:

javascript

1// What the heck is 86400000 for? 2setTimeout(blastOff, 86400000);

Good:

javascript

1// Declare them as capitalized named constants. 2const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000; //86400000; 3 4setTimeout(blastOff, MILLISECONDS_PER_DAY);

⬆ back to top

Use explanatory variables

Bad:

javascript

1const address = "One Infinite Loop, Cupertino 95014"; 2const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 3saveCityZipCode( 4 address.match(cityZipCodeRegex)[1], 5 address.match(cityZipCodeRegex)[2] 6);

Good:

javascript

1const address = "One Infinite Loop, Cupertino 95014"; 2const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; 3const [_, city, zipCode] = address.match(cityZipCodeRegex) || []; 4saveCityZipCode(city, zipCode);

⬆ back to top

Avoid Mental Mapping

Explicit is better than implicit.

Bad:

javascript

1const locations = ["Austin", "New York", "San Francisco"]; 2locations.forEach(l => { 3 doStuff(); 4 doSomeOtherStuff(); 5 // ... 6 // ... 7 // ... 8 // Wait, what is `l` for again? 9 dispatch(l); 10});

Good:

javascript

1const locations = ["Austin", "New York", "San Francisco"]; 2locations.forEach(location => { 3 doStuff(); 4 doSomeOtherStuff(); 5 // ... 6 // ... 7 // ... 8 dispatch(location); 9});

⬆ back to top

Don't add unneeded context

If your class/object name tells you something, don't repeat that in your

variable name.

Bad:

javascript

1const Car = { 2 carMake: "Honda", 3 carModel: "Accord", 4 carColor: "Blue" 5}; 6 7function paintCar(car, color) { 8 car.carColor = color; 9}

Good:

javascript

1const Car = { 2 make: "Honda", 3 model: "Accord", 4 color: "Blue" 5}; 6 7function paintCar(car, color) { 8 car.color = color; 9}

⬆ back to top

Use default parameters instead of short circuiting or conditionals

Default parameters are often cleaner than short circuiting. Be aware that if you

use them, your function will only provide default values for undefined

arguments. Other "falsy" values such as '', "", false, null, 0, and

NaN, will not be replaced by a default value.

Bad:

javascript

1function createMicrobrewery(name) { 2 const breweryName = name || "Hipster Brew Co."; 3 // ... 4}

Good:

javascript

1function createMicrobrewery(name = "Hipster Brew Co.") { 2 // ... 3}

⬆ back to top

Functions

Function arguments (2 or fewer ideally)

Limiting the amount of function parameters is incredibly important because it

makes testing your function easier. Having more than three leads to a

combinatorial explosion where you have to test tons of different cases with

each separate argument.

One or two arguments is the ideal case, and three should be avoided if possible.

Anything more than that should be consolidated. Usually, if you have

more than two arguments then your function is trying to do too much. In cases

where it's not, most of the time a higher-level object will suffice as an

argument.

Since JavaScript allows you to make objects on the fly, without a lot of class

boilerplate, you can use an object if you are finding yourself needing a

lot of arguments.

To make it obvious what properties the function expects, you can use the ES2015/ES6

destructuring syntax. This has a few advantages:

When someone looks at the function signature, it's immediately clear what

properties are being used.

It can be used to simulate named parameters.

Destructuring also clones the specified primitive values of the argument

object passed into the function. This can help prevent side effects. Note:

objects and arrays that are destructured from the argument object are NOT

cloned.

Linters can warn you about unused properties, which would be impossible

without destructuring.

Bad:

javascript

1function createMenu(title, body, buttonText, cancellable) { 2 // ... 3} 4 5createMenu("Foo", "Bar", "Baz", true);

Good:

javascript

1function createMenu({ title, body, buttonText, cancellable }) { 2 // ... 3} 4 5createMenu({ 6 title: "Foo", 7 body: "Bar", 8 buttonText: "Baz", 9 cancellable: true 10});

⬆ back to top

Functions should do one thing

This is by far the most important rule in software engineering. When functions

do more than one thing, they are harder to compose, test, and reason about.

When you can isolate a function to just one action, it can be refactored

easily and your code will read much cleaner. If you take nothing else away from

this guide other than this, you'll be ahead of many developers.

Bad:

javascript

1function emailClients(clients) { 2 clients.forEach(client => { 3 const clientRecord = database.lookup(client); 4 if (clientRecord.isActive()) { 5 email(client); 6 } 7 }); 8}

Good:

javascript

1function emailActiveClients(clients) { 2 clients.filter(isActiveClient).forEach(email); 3} 4 5function isActiveClient(client) { 6 const clientRecord = database.lookup(client); 7 return clientRecord.isActive(); 8}

⬆ back to top

Function names should say what they do

Bad:

javascript

1function addToDate(date, month) { 2 // ... 3} 4 5const date = new Date(); 6 7// It's hard to tell from the function name what is added 8addToDate(date, 1);

Good:

javascript

1function addMonthToDate(month, date) { 2 // ... 3} 4 5const date = new Date(); 6addMonthToDate(1, date);

⬆ back to top

Functions should only be one level of abstraction

When you have more than one level of abstraction your function is usually

doing too much. Splitting up functions leads to reusability and easier

testing.

Bad:

javascript

1function parseBetterJSAlternative(code) { 2 const REGEXES = [\ 3 // ...\ 4 ]; 5 6 const statements = code.split(" "); 7 const tokens = []; 8 REGEXES.forEach(REGEX => { 9 statements.forEach(statement => { 10 // ... 11 }); 12 }); 13 14 const ast = []; 15 tokens.forEach(token => { 16 // lex... 17 }); 18 19 ast.forEach(node => { 20 // parse... 21 }); 22}

Good:

javascript

1function parseBetterJSAlternative(code) { 2 const tokens = tokenize(code); 3 const syntaxTree = parse(tokens); 4 syntaxTree.forEach(node => { 5 // parse... 6 }); 7} 8 9function tokenize(code) { 10 const REGEXES = [\ 11 // ...\ 12 ]; 13 14 const statements = code.split(" "); 15 const tokens = []; 16 REGEXES.forEach(REGEX => { 17 statements.forEach(statement => { 18 tokens.push(/* ... */); 19 }); 20 }); 21 22 return tokens; 23} 24 25function parse(tokens) { 26 const syntaxTree = []; 27 tokens.forEach(token => { 28 syntaxTree.push(/* ... */); 29 }); 30 31 return syntaxTree; 32}

⬆ back to top

Remove duplicate code

Do your absolute best to avoid duplicate code. Duplicate code is bad because it

means that there's more than one place to alter something if you need to change

some logic.

Imagine if you run a restaurant and you keep track of your inventory: all your

tomatoes, onions, garlic, spices, etc. If you have multiple lists that

you keep this on, then all have to be updated when you serve a dish with

tomatoes in them. If you only have one list, there's only one place to update!

Oftentimes you have duplicate code because you have two or more slightly

different things, that share a lot in common, but their differences force you

to have two or more separate functions that do much of the same things. Removing

duplicate code means creating an abstraction that can handle this set of

different things with just one function/module/class.

Getting the abstraction right is critical, that's why you should follow the

SOLID principles laid out in the _Classes_ section. Bad abstractions can be

worse than duplicate code, so be careful! Having said this, if you can make

a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself

updating multiple places anytime you want to change one thing.

Bad:

javascript

1function showDeveloperList(developers) { 2 developers.forEach(developer => { 3 const expectedSalary = developer.calculateExpectedSalary(); 4 const experience = developer.getExperience(); 5 const githubLink = developer.getGithubLink(); 6 const data = { 7 expectedSalary, 8 experience, 9 githubLink 10 }; 11 12 render(data); 13 }); 14} 15 16function showManagerList(managers) { 17 managers.forEach(manager => { 18 const expectedSalary = manager.calculateExpectedSalary(); 19 const experience = manager.getExperience(); 20 const portfolio = manager.getMBAProjects(); 21 const data = { 22 expectedSalary, 23 experience, 24 portfolio 25 }; 26 27 render(data); 28 }); 29}

Good:

javascript

1function showEmployeeList(employees) { 2 employees.forEach(employee => { 3 const expectedSalary = employee.calculateExpectedSalary(); 4 const experience = employee.getExperience(); 5 6 const data = { 7 expectedSalary, 8 experience 9 }; 10 11 switch (employee.type) { 12 case "manager": 13 data.portfolio = employee.getMBAProjects(); 14 break; 15 case "developer": 16 data.githubLink = employee.getGithubLink(); 17 break; 18 } 19 20 render(data); 21 }); 22}

⬆ back to top

Set default objects with Object.assign

Bad:

javascript

1const menuConfig = { 2 title: null, 3 body: "Bar", 4 buttonText: null, 5 cancellable: true 6}; 7 8function createMenu(config) { 9 config.title = config.title || "Foo"; 10 config.body = config.body || "Bar"; 11 config.buttonText = config.buttonText || "Baz"; 12 config.cancellable = 13 config.cancellable !== undefined ? config.cancellable : true; 14} 15 16createMenu(menuConfig);

Good:

javascript

1const menuConfig = { 2 title: "Order", 3 // User did not include 'body' key 4 buttonText: "Send", 5 cancellable: true 6}; 7 8function createMenu(config) { 9 let finalConfig = Object.assign( 10 { 11 title: "Foo", 12 body: "Bar", 13 buttonText: "Baz", 14 cancellable: true 15 }, 16 config 17 ); 18 return finalConfig 19 // config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true} 20 // ... 21} 22 23createMenu(menuConfig);

⬆ back to top

Don't use flags as function parameters

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.

Bad:

javascript

1function createFile(name, temp) { 2 if (temp) { 3 fs.create(`./temp/${name}`); 4 } else { 5 fs.create(name); 6 } 7}

Good:

javascript

1function createFile(name) { 2 fs.create(name); 3} 4 5function createTempFile(name) { 6 createFile(`./temp/${name}`); 7}

⬆ back to top

Avoid Side Effects (part 1)

A function produces a side effect if it does anything other than take a value in

and return another value or values. A side effect could be writing to a file,

modifying some global variable, or accidentally wiring all your money to a

stranger.

Now, you do need to have side effects in a program on occasion. Like the previous

example, you might need to write to a file. What you want to do is to

centralize where you are doing this. Don't have several functions and classes

that write to a particular file. Have one service that does it. One and only one.

The main point is to avoid common pitfalls like sharing state between objects

without any structure, using mutable data types that can be written to by anything,

and not centralizing where your side effects occur. If you can do this, you will

be happier than the vast majority of other programmers.

Bad:

javascript

1// Global variable referenced by following function. 2// If we had another function that used this name, now it'd be an array and it could break it. 3let name = "Ryan McDermott"; 4 5function splitIntoFirstAndLastName() { 6 name = name.split(" "); 7} 8 9splitIntoFirstAndLastName(); 10 11console.log(name); // ['Ryan', 'McDermott'];

Good:

javascript

1function splitIntoFirstAndLastName(name) { 2 return name.split(" "); 3} 4 5const name = "Ryan McDermott"; 6const newName = splitIntoFirstAndLastName(name); 7 8console.log(name); // 'Ryan McDermott'; 9console.log(newName); // ['Ryan', 'McDermott'];

⬆ back to top

Avoid Side Effects (part 2)

In JavaScript, some values are unchangeable (immutable) and some are changeable

(mutable). Objects and arrays are two kinds of mutable values so it's important

to handle them carefully when they're passed as parameters to a function. A

JavaScript function can change an object's properties or alter the contents of

an array which could easily cause bugs elsewhere.

Suppose there's a function that accepts an array parameter representing a

shopping cart. If the function makes a change in that shopping cart array -

by adding an item to purchase, for example - then any other function that

uses that same cart array will be affected by this addition. That may be

great, however it could also be bad. Let's imagine a bad situation:

The user clicks the "Purchase" button which calls a purchase function that

spawns a network request and sends the cart array to the server. Because

of a bad network connection, the purchase function has to keep retrying the

request. Now, what if in the meantime the user accidentally clicks an "Add to Cart"

button on an item they don't actually want before the network request begins?

If that happens and the network request begins, then that purchase function

will send the accidentally added item because the cart array was modified.

A great solution would be for the addItemToCart function to always clone the

cart, edit it, and return the clone. This would ensure that functions that are still

using the old shopping cart wouldn't be affected by the changes.

Two caveats to mention to this approach:

There might be cases where you actually want to modify the input object,

but when you adopt this programming practice you will find that those cases

are pretty rare. Most things can be refactored to have no side effects!

Cloning big objects can be very expensive in terms of performance. Luckily,

this isn't a big issue in practice because there are

great libraries that allow

this kind of programming approach to be fast and not as memory intensive as

it would be for you to manually clone objects and arrays.

Bad:

javascript

1const addItemToCart = (cart, item) => { 2 cart.push({ item, date: Date.now() }); 3};

Good:

javascript

1const addItemToCart = (cart, item) => { 2 return [...cart, { item, date: Date.now() }]; 3};

⬆ back to top

Don't write to global functions

Polluting globals is a bad practice in JavaScript because you could clash with another

library and the user of your API would be none-the-wiser until they get an

exception in production. Let's think about an example: what if you wanted to

extend JavaScript's native Array method to have a diff method that could

show the difference between two arrays? You could write your new function

to the Array.prototype, but it could clash with another library that tried

to do the same thing. What if that other library was just using diff to find

the difference between the first and last elements of an array? This is why it

would be much better to just use ES2015/ES6 classes and simply extend the Array global.

Bad:

javascript

1Array.prototype.diff = function diff(comparisonArray) { 2 const hash = new Set(comparisonArray); 3 return this.filter(elem => !hash.has(elem)); 4};

Good:

javascript

1class SuperArray extends Array { 2 diff(comparisonArray) { 3 const hash = new Set(comparisonArray); 4 return this.filter(elem => !hash.has(elem)); 5 } 6}

⬆ back to top

Favor functional programming over imperative programming

JavaScript isn't a functional language in the way that Haskell is, but it has

a functional flavor to it. Functional languages can be cleaner and easier to test.

Favor this style of programming when you can.

Bad:

javascript

1const programmerOutput = [\ 2 {\ 3 name: "Uncle Bobby",\ 4 linesOfCode: 500\ 5 },\ 6 {\ 7 name: "Suzie Q",\ 8 linesOfCode: 1500\ 9 },\ 10 {\ 11 name: "Jimmy Gosling",\ 12 linesOfCode: 150\ 13 },\ 14 {\ 15 name: "Gracie Hopper",\ 16 linesOfCode: 1000\ 17 }\ 18]; 19 20let totalOutput = 0; 21 22for (let i = 0; i < programmerOutput.length; i++) { 23 totalOutput += programmerOutput[i].linesOfCode; 24}

Good:

javascript

1const programmerOutput = [\ 2 {\ 3 name: "Uncle Bobby",\ 4 linesOfCode: 500\ 5 },\ 6 {\ 7 name: "Suzie Q",\ 8 linesOfCode: 1500\ 9 },\ 10 {\ 11 name: "Jimmy Gosling",\ 12 linesOfCode: 150\ 13 },\ 14 {\ 15 name: "Gracie Hopper",\ 16 linesOfCode: 1000\ 17 }\ 18]; 19 20const totalOutput = programmerOutput.reduce( 21 (totalLines, output) => totalLines + output.linesOfCode, 22 0 23);

⬆ back to top

Encapsulate conditionals

Bad:

javascript

1if (fsm.state === "fetching" && isEmpty(listNode)) { 2 // ... 3}

Good:

javascript

1function shouldShowSpinner(fsm, listNode) { 2 return fsm.state === "fetching" && isEmpty(listNode); 3} 4 5if (shouldShowSpinner(fsmInstance, listNodeInstance)) { 6 // ... 7}

⬆ back to top

Avoid negative conditionals

Bad:

javascript

1function isDOMNodeNotPresent(node) { 2 // ... 3} 4 5if (!isDOMNodeNotPresent(node)) { 6 // ... 7}

Good:

javascript

1function isDOMNodePresent(node) { 2 // ... 3} 4 5if (isDOMNodePresent(node)) { 6 // ... 7}

⬆ back to top

Avoid conditionals

This seems like an impossible task. Upon first hearing this, most people say,

"how am I supposed to do anything without an if statement?" The answer is that

you can use polymorphism to achieve the same task in many cases. The second

question is usually, "well that's great but why would I want to do that?" The

answer is a previous clean code concept we learned: a function should only do

one thing. When you have classes and functions that have if statements, you

are telling your user that your function does more than one thing. Remember,

just do one thing.

Bad:

javascript

1class Airplane { 2 // ... 3 getCruisingAltitude() { 4 switch (this.type) { 5 case "777": 6 return this.getMaxAltitude() - this.getPassengerCount(); 7 case "Air Force One": 8 return this.getMaxAltitude(); 9 case "Cessna": 10 return this.getMaxAltitude() - this.getFuelExpenditure(); 11 } 12 } 13}

Good:

javascript

1class Airplane { 2 // ... 3} 4 5class Boeing777 extends Airplane { 6 // ... 7 getCruisingAltitude() { 8 return this.getMaxAltitude() - this.getPassengerCount(); 9 } 10} 11 12class AirForceOne extends Airplane { 13 // ... 14 getCruisingAltitude() { 15 return this.getMaxAltitude(); 16 } 17} 18 19class Cessna extends Airplane { 20 // ... 21 getCruisingAltitude() { 22 return this.getMaxAltitude() - this.getFuelExpenditure(); 23 } 24}

⬆ back to top

Avoid type-checking (part 1)

JavaScript is untyped, which means your functions can take any type of argument.

Sometimes you are bitten by this freedom and it becomes tempting to do

type-checking in your functions. There are many ways to avoid having to do this.

The first thing to consider is consistent APIs.

Bad:

javascript

1function travelToTexas(vehicle) { 2 if (vehicle instanceof Bicycle) { 3 vehicle.pedal(this.currentLocation, new Location("texas")); 4 } else if (vehicle instanceof Car) { 5 vehicle.drive(this.currentLocation, new Location("texas")); 6 } 7}

Good:

javascript

1function travelToTexas(vehicle) { 2 vehicle.move(this.currentLocation, new Location("texas")); 3}

⬆ back to top

Avoid type-checking (part 2)

If you are working with basic primitive values like strings and integers,

and you can't use polymorphism but you still feel the need to type-check,

you should consider using TypeScript. It is an excellent alternative to normal

JavaScript, as it provides you with static typing on top of standard JavaScript

syntax. The problem with manually type-checking normal JavaScript is that

doing it well requires so much extra verbiage that the faux "type-safety" you get

doesn't make up for the lost readability. Keep your JavaScript clean, write

good tests, and have good code reviews. Otherwise, do all of that but with

TypeScript (which, like I said, is a great alternative!).

Bad:

javascript

1function combine(val1, val2) { 2 if ( 3 (typeof val1 === "number" && typeof val2 === "number") || 4 (typeof val1 === "string" && typeof val2 === "string") 5 ) { 6 return val1 + val2; 7 } 8 9 throw new Error("Must be of type String or Number"); 10}

Good:

javascript

1function combine(val1, val2) { 2 return val1 + val2; 3}

⬆ back to top

Don't over-optimize

Modern browsers do a lot of optimization under-the-hood at runtime. A lot of

times, if you are optimizing then you are just wasting your time. There are good

resources

for seeing where optimization is lacking. Target those in the meantime, until

they are fixed if they can be.

Bad:

javascript

1// On old browsers, each iteration with uncached `list.length` would be costly 2// because of `list.length` recomputation. In modern browsers, this is optimized. 3for (let i = 0, len = list.length; i < len; i++) { 4 // ... 5}

Good:

javascript

1for (let i = 0; i < list.length; i++) { 2 // ... 3}

⬆ back to top

Remove dead code

Dead code is just as bad as duplicate code. There's no reason to keep it in

your codebase. If it's not being called, get rid of it! It will still be safe

in your version history if you still need it.

Bad:

javascript

1function oldRequestModule(url) { 2 // ... 3} 4 5function newRequestModule(url) { 6 // ... 7} 8 9const req = newRequestModule; 10inventoryTracker("apples", req, "www.inventory-awesome.io");

Good:

javascript

1function newRequestModule(url) { 2 // ... 3} 4 5const req = newRequestModule; 6inventoryTracker("apples", req, "www.inventory-awesome.io");

⬆ back to top

Objects and Data Structures

Use getters and setters

Using getters and setters to access data on objects could be better than simply

looking for a property on an object. "Why?" you might ask. Well, here's an

unorganized list of reasons why:

When you want to do more beyond getting an object property, you don't have

to look up and change every accessor in your codebase.

Makes adding validation simple when doing a set.

Encapsulates the internal representation.

Easy to add logging and error handling when getting and setting.

You can lazy load your object's properties, let's say getting it from a

server.

Bad:

javascript

1function makeBankAccount() { 2 // ... 3 4 return { 5 balance: 0 6 // ... 7 }; 8} 9 10const account = makeBankAccount(); 11account.balance = 100;

Good:

javascript

1function makeBankAccount() { 2 // this one is private 3 let balance = 0; 4 5 // a "getter", made public via the returned object below 6 function getBalance() { 7 return balance; 8 } 9 10 // a "setter", made public via the returned object below 11 function setBalance(amount) { 12 // ... validate before updating the balance 13 balance = amount; 14 } 15 16 return { 17 // ... 18 getBalance, 19 setBalance 20 }; 21} 22 23const account = makeBankAccount(); 24account.setBalance(100);

⬆ back to top

Make objects have private members

This can be accomplished through closures (for ES5 and below).

Bad:

javascript

1const Employee = function(name) { 2 this.name = name; 3}; 4 5Employee.prototype.getName = function getName() { 6 return this.name; 7}; 8 9const employee = new Employee("John Doe"); 10console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe 11delete employee.name; 12console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined

Good:

javascript

1function makeEmployee(name) { 2 return { 3 getName() { 4 return name; 5 } 6 }; 7} 8 9const employee = makeEmployee("John Doe"); 10console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe 11delete employee.name; 12console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe

⬆ back to top

Classes

Prefer ES2015/ES6 classes over ES5 plain functions

It's very difficult to get readable class inheritance, construction, and method

definitions for classical ES5 classes. If you need inheritance (and be aware

that you might not), then prefer ES2015/ES6 classes. However, prefer small functions over

classes until you find yourself needing larger and more complex objects.

Bad:

javascript

1const Animal = function(age) { 2 if (!(this instanceof Animal)) { 3 throw new Error("Instantiate Animal with `new`"); 4 } 5 6 this.age = age; 7}; 8 9Animal.prototype.move = function move() {}; 10 11const Mammal = function(age, furColor) { 12 if (!(this instanceof Mammal)) { 13 throw new Error("Instantiate Mammal with `new`"); 14 } 15 16 Animal.call(this, age); 17 this.furColor = furColor; 18}; 19 20Mammal.prototype = Object.create(Animal.prototype); 21Mammal.prototype.constructor = Mammal; 22Mammal.prototype.liveBirth = function liveBirth() {}; 23 24const Human = function(age, furColor, languageSpoken) { 25 if (!(this instanceof Human)) { 26 throw new Error("Instantiate Human with `new`"); 27 } 28 29 Mammal.call(this, age, furColor); 30 this.languageSpoken = languageSpoken; 31}; 32 33Human.prototype = Object.create(Mammal.prototype); 34Human.prototype.constructor = Human; 35Human.prototype.speak = function speak() {};

Good:

javascript

1class Animal { 2 constructor(age) { 3 this.age = age; 4 } 5 6 move() { 7 /* ... */ 8 } 9} 10 11class Mammal extends Animal { 12 constructor(age, furColor) { 13 super(age); 14 this.furColor = furColor; 15 } 16 17 liveBirth() { 18 /* ... */ 19 } 20} 21 22class Human extends Mammal { 23 constructor(age, furColor, languageSpoken) { 24 super(age, furColor); 25 this.languageSpoken = languageSpoken; 26 } 27 28 speak() { 29 /* ... */ 30 } 31}

⬆ back to top

Use method chaining

This pattern is very useful in JavaScript and you see it in many libraries such

as jQuery and Lodash. It allows your code to be expressive, and less verbose.

For that reason, I say, use method chaining and take a look at how clean your code

will be. In your class functions, simply return this at the end of every function,

and you can chain further class methods onto it.

Bad:

javascript

1class Car { 2 constructor(make, model, color) { 3 this.make = make; 4 this.model = model; 5 this.color = color; 6 } 7 8 setMake(make) { 9 this.make = make; 10 } 11 12 setModel(model) { 13 this.model = model; 14 } 15 16 setColor(color) { 17 this.color = color; 18 } 19 20 save() { 21 console.log(this.make, this.model, this.color); 22 } 23} 24 25const car = new Car("Ford", "F-150", "red"); 26car.setColor("pink"); 27car.save();

Good:

javascript

1class Car { 2 constructor(make, model, color) { 3 this.make = make; 4 this.model = model; 5 this.color = color; 6 } 7 8 setMake(make) { 9 this.make = make; 10 // NOTE: Returning this for chaining 11 return this; 12 } 13 14 setModel(model) { 15 this.model = model; 16 // NOTE: Returning this for chaining 17 return this; 18 } 19 20 setColor(color) { 21 this.color = color; 22 // NOTE: Returning this for chaining 23 return this; 24 } 25 26 save() { 27 console.log(this.make, this.model, this.color); 28 // NOTE: Returning this for chaining 29 return this; 30 } 31} 32 33const car = new Car("Ford", "F-150", "red").setColor("pink").save();

⬆ back to top

Prefer composition over inheritance

As stated famously in _Design Patterns_ by the Gang of Four,

you should prefer composition over inheritance where you can. There are lots of

good reasons to use inheritance and lots of good reasons to use composition.

The main point for this maxim is that if your mind instinctively goes for

inheritance, try to think if composition could model your problem better. In some

cases it can.

You might be wondering then, "when should I use inheritance?" It

depends on your problem at hand, but this is a decent list of when inheritance

makes more sense than composition:

Your inheritance represents an "is-a" relationship and not a "has-a"

relationship (Human->Animal vs. User->UserDetails).

You can reuse code from the base classes (Humans can move like all animals).

You want to make global changes to derived classes by changing a base class.

(Change the caloric expenditure of all animals when they move).

Bad:

javascript

1class Employee { 2 constructor(name, email) { 3 this.name = name; 4 this.email = email; 5 } 6 7 // ... 8} 9 10// Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee 11class EmployeeTaxData extends Employee { 12 constructor(ssn, salary) { 13 super(); 14 this.ssn = ssn; 15 this.salary = salary; 16 } 17 18 // ... 19}

Good:

javascript

1class EmployeeTaxData { 2 constructor(ssn, salary) { 3 this.ssn = ssn; 4 this.salary = salary; 5 } 6 7 // ... 8} 9 10class Employee { 11 constructor(name, email) { 12 this.name = name; 13 this.email = email; 14 } 15 16 setTaxData(ssn, salary) { 17 this.taxData = new EmployeeTaxData(ssn, salary); 18 } 19 // ... 20}

⬆ back to top

SOLID

Single Responsibility Principle (SRP)

As stated in Clean Code, "There should never be more than one reason for a class

to change". It's tempting to jam-pack a class with a lot of functionality, like

when you can only take one suitcase on your flight. The issue with this is

that your class won't be conceptually cohesive and it will give it many reasons

to change. Minimizing the amount of times you need to change a class is important.

It's important because if too much functionality is in one class and you modify

a piece of it, it can be difficult to understand how that will affect other

dependent modules in your codebase.

Bad:

javascript

1class UserSettings { 2 constructor(user) { 3 this.user = user; 4 } 5 6 changeSettings(settings) { 7 if (this.verifyCredentials()) { 8 // ... 9 } 10 } 11 12 verifyCredentials() { 13 // ... 14 } 15}

Good:

javascript

1class UserAuth { 2 constructor(user) { 3 this.user = user; 4 } 5 6 verifyCredentials() { 7 // ... 8 } 9} 10 11class UserSettings { 12 constructor(user) { 13 this.user = user; 14 this.auth = new UserAuth(user); 15 } 16 17 changeSettings(settings) { 18 if (this.auth.verifyCredentials()) { 19 // ... 20 } 21 } 22}

⬆ back to top

Open/Closed Principle (OCP)

As stated by Bertrand Meyer, "software entities (classes, modules, functions,

etc.) should be open for extension, but closed for modification." What does that

mean though? This principle basically states that you should allow users to

add new functionalities without changing existing code.

Bad:

javascript

1class AjaxAdapter extends Adapter { 2 constructor() { 3 super(); 4 this.name = "ajaxAdapter"; 5 } 6} 7 8class NodeAdapter extends Adapter { 9 constructor() { 10 super(); 11 this.name = "nodeAdapter"; 12 } 13} 14 15class HttpRequester { 16 constructor(adapter) { 17 this.adapter = adapter; 18 } 19 20 fetch(url) { 21 if (this.adapter.name === "ajaxAdapter") { 22 return makeAjaxCall(url).then(response => { 23 // transform response and return 24 }); 25 } else if (this.adapter.name === "nodeAdapter") { 26 return makeHttpCall(url).then(response => { 27 // transform response and return 28 }); 29 } 30 } 31} 32 33function makeAjaxCall(url) { 34 // request and return promise 35} 36 37function makeHttpCall(url) { 38 // request and return promise 39}

Good:

javascript

1class AjaxAdapter extends Adapter { 2 constructor() { 3 super(); 4 this.name = "ajaxAdapter"; 5 } 6 7 request(url) { 8 // request and return promise 9 } 10} 11 12class NodeAdapter extends Adapter { 13 constructor() { 14 super(); 15 this.name = "nodeAdapter"; 16 } 17 18 request(url) { 19 // request and return promise 20 } 21} 22 23class HttpRequester { 24 constructor(adapter) { 25 this.adapter = adapter; 26 } 27 28 fetch(url) { 29 return this.adapter.request(url).then(response => { 30 // transform response and return 31 }); 32 } 33}

⬆ back to top

Liskov Substitution Principle (LSP)

This is a scary term for a very simple concept. It's formally defined as "If S

is a subtype of T, then objects of type T may be replaced with objects of type S

(i.e., objects of type S may substitute objects of type T) without altering any

of the desirable properties of that program (correctness, task performed,

etc.)." That's an even scarier definition.

The best explanation for this is if you have a parent class and a child class,

then the base class and child class can be used interchangeably without getting

incorrect results. This might still be confusing, so let's take a look at the

classic Square-Rectangle example. Mathematically, a square is a rectangle, but

if you model it using the "is-a" relationship via inheritance, you quickly

get into trouble.

Bad:

javascript

1class Rectangle { 2 constructor() { 3 this.width = 0; 4 this.height = 0; 5 } 6 7 setColor(color) { 8 // ... 9 } 10 11 render(area) { 12 // ... 13 } 14 15 setWidth(width) { 16 this.width = width; 17 } 18 19 setHeight(height) { 20 this.height = height; 21 } 22 23 getArea() { 24 return this.width * this.height; 25 } 26} 27 28class Square extends Rectangle { 29 setWidth(width) { 30 this.width = width; 31 this.height = width; 32 } 33 34 setHeight(height) { 35 this.width = height; 36 this.height = height; 37 } 38} 39 40function renderLargeRectangles(rectangles) { 41 rectangles.forEach(rectangle => { 42 rectangle.setWidth(4); 43 rectangle.setHeight(5); 44 const area = rectangle.getArea(); // BAD: Returns 25 for Square. Should be 20. 45 rectangle.render(area); 46 }); 47} 48 49const rectangles = [new Rectangle(), new Rectangle(), new Square()]; 50renderLargeRectangles(rectangles);

Good:

javascript

1class Shape { 2 setColor(color) { 3 // ... 4 } 5 6 render(area) { 7 // ... 8 } 9} 10 11class Rectangle extends Shape { 12 constructor(width, height) { 13 super(); 14 this.width = width; 15 this.height = height; 16 } 17 18 getArea() { 19 return this.width * this.height; 20 } 21} 22 23class Square extends Shape { 24 constructor(length) { 25 super(); 26 this.length = length; 27 } 28 29 getArea() { 30 return this.length * this.length; 31 } 32} 33 34function renderLargeShapes(shapes) { 35 shapes.forEach(shape => { 36 const area = shape.getArea(); 37 shape.render(area); 38 }); 39} 40 41const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)]; 42renderLargeShapes(shapes);

⬆ back to top

Interface Segregation Principle (ISP)

JavaScript doesn't have interfaces so this principle doesn't apply as strictly

as others. However, it's important and relevant even with JavaScript's lack of

type system.

ISP states that "Clients should not be forced to depend upon interfaces that

they do not use." Interfaces are implicit contracts in JavaScript because of

duck typing.

A good example to look at that demonstrates this principle in JavaScript is for

classes that require large settings objects. Not requiring clients to setup

huge amounts of options is beneficial, because most of the time they won't need

all of the settings. Making them optional helps prevent having a

"fat interface".

Bad:

javascript

1class DOMTraverser { 2 constructor(settings) { 3 this.settings = settings; 4 this.setup(); 5 } 6 7 setup() { 8 this.rootNode = this.settings.rootNode; 9 this.settings.animationModule.setup(); 10 } 11 12 traverse() { 13 // ... 14 } 15} 16 17const $ = new DOMTraverser({ 18 rootNode: document.getElementsByTagName("body"), 19 animationModule() {} // Most of the time, we won't need to animate when traversing. 20 // ... 21});

Good:

javascript

1class DOMTraverser { 2 constructor(settings) { 3 this.settings = settings; 4 this.options = settings.options; 5 this.setup(); 6 } 7 8 setup() { 9 this.rootNode = this.settings.rootNode; 10 this.setupOptions(); 11 } 12 13 setupOptions() { 14 if (this.options.animationModule) { 15 // ... 16 } 17 } 18 19 traverse() { 20 // ... 21 } 22} 23 24const $ = new DOMTraverser({ 25 rootNode: document.getElementsByTagName("body"), 26 options: { 27 animationModule() {} 28 } 29});

⬆ back to top

Dependency Inversion Principle (DIP)

This principle states two essential things:

High-level modules should not depend on low-level modules. Both should

depend on abstractions.

Abstractions should not depend upon details. Details should depend on

abstractions.

This can be hard to understand at first, but if you've worked with AngularJS,

you've seen an implementation of this principle in the form of Dependency

Injection (DI). While they are not identical concepts, DIP keeps high-level

modules from knowing the details of its low-level modules and setting them up.

It can accomplish this through DI. A huge benefit of this is that it reduces

the coupling between modules. Coupling is a very bad development pattern because

it makes your code hard to refactor.

As stated previously, JavaScript doesn't have interfaces so the abstractions

that are depended upon are implicit contracts. That is to say, the methods

and properties that an object/class exposes to another object/class. In the

example below, the implicit contract is that any Request module for an

InventoryTracker will have a requestItems method.

Bad:

javascript

1class InventoryRequester { 2 constructor() { 3 this.REQ_METHODS = ["HTTP"]; 4 } 5 6 requestItem(item) { 7 // ... 8 } 9} 10 11class InventoryTracker { 12 constructor(items) { 13 this.items = items; 14 15 // BAD: We have created a dependency on a specific request implementation. 16 // We should just have requestItems depend on a request method: `request` 17 this.requester = new InventoryRequester(); 18 } 19 20 requestItems() { 21 this.items.forEach(item => { 22 this.requester.requestItem(item); 23 }); 24 } 25} 26 27const inventoryTracker = new InventoryTracker(["apples", "bananas"]); 28inventoryTracker.requestItems();

Good:

javascript

1class InventoryTracker { 2 constructor(items, requester) { 3 this.items = items; 4 this.requester = requester; 5 } 6 7 requestItems() { 8 this.items.forEach(item => { 9 this.requester.requestItem(item); 10 }); 11 } 12} 13 14class InventoryRequesterV1 { 15 constructor() { 16 this.REQ_METHODS = ["HTTP"]; 17 } 18 19 requestItem(item) { 20 // ... 21 } 22} 23 24class InventoryRequesterV2 { 25 constructor() { 26 this.REQ_METHODS = ["WS"]; 27 } 28 29 requestItem(item) { 30 // ... 31 } 32} 33 34// By constructing our dependencies externally and injecting them, we can easily 35// substitute our request module for a fancy new one that uses WebSockets. 36const inventoryTracker = new InventoryTracker( 37 ["apples", "bananas"], 38 new InventoryRequesterV2() 39); 40inventoryTracker.requestItems();

⬆ back to top

Testing

Testing is more important than shipping. If you have no tests or an

inadequate amount, then every time you ship code you won't be sure that you

didn't break anything. Deciding on what constitutes an adequate amount is up

to your team, but having 100% coverage (all statements and branches) is how

you achieve very high confidence and developer peace of mind. This means that

in addition to having a great testing framework, you also need to use a

good coverage tool.

There's no excuse to not write tests. There are plenty of good JS test frameworks, so find one that your team prefers.

When you find one that works for your team, then aim to always write tests

for every new feature/module you introduce. If your preferred method is

Test Driven Development (TDD), that is great, but the main point is to just

make sure you are reaching your coverage goals before launching any feature,

or refactoring an existing one.

Single concept per test

Bad:

javascript

1import assert from "assert"; 2 3describe("MomentJS", () => { 4 it("handles date boundaries", () => { 5 let date; 6 7 date = new MomentJS("1/1/2015"); 8 date.addDays(30); 9 assert.equal("1/31/2015", date); 10 11 date = new MomentJS("2/1/2016"); 12 date.addDays(28); 13 assert.equal("02/29/2016", date); 14 15 date = new MomentJS("2/1/2015"); 16 date.addDays(28); 17 assert.equal("03/01/2015", date); 18 }); 19});

Good:

javascript

1import assert from "assert"; 2 3describe("MomentJS", () => { 4 it("handles 30-day months", () => { 5 const date = new MomentJS("1/1/2015"); 6 date.addDays(30); 7 assert.equal("1/31/2015", date); 8 }); 9 10 it("handles leap year", () => { 11 const date = new MomentJS("2/1/2016"); 12 date.addDays(28); 13 assert.equal("02/29/2016", date); 14 }); 15 16 it("handles non-leap year", () => { 17 const date = new MomentJS("2/1/2015"); 18 date.addDays(28); 19 assert.equal("03/01/2015", date); 20 }); 21});

⬆ back to top

Concurrency

Use Promises, not callbacks

Callbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6,

Promises are a built-in global type. Use them!

Bad:

javascript

1import { get } from "request"; 2import { writeFile } from "fs"; 3 4get( 5 "https://en.wikipedia.org/wiki/Robert_Cecil_Martin", 6 (requestErr, response, body) => { 7 if (requestErr) { 8 console.error(requestErr); 9 } else { 10 writeFile("article.html", body, writeErr => { 11 if (writeErr) { 12 console.error(writeErr); 13 } else { 14 console.log("File written"); 15 } 16 }); 17 } 18 } 19);

Good:

javascript

1import { get } from "request-promise"; 2import { writeFile } from "fs-extra"; 3 4get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin") 5 .then(body => { 6 return writeFile("article.html", body); 7 }) 8 .then(() => { 9 console.log("File written"); 10 }) 11 .catch(err => { 12 console.error(err); 13 });

⬆ back to top

Async/Await are even cleaner than Promises

Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await

which offer an even cleaner solution. All you need is a function that is prefixed

in an async keyword, and then you can write your logic imperatively without

a then chain of functions. Use this if you can take advantage of ES2017/ES8 features

today!

Bad:

javascript

Good:

javascript

1import { get } from "request-promise"; 2import { writeFile } from "fs-extra"; 3 4async function getCleanCodeArticle() { 5 try { 6 const body = await get( 7 "https://en.wikipedia.org/wiki/Robert_Cecil_Martin" 8 ); 9 await writeFile("article.html", body); 10 console.log("File written"); 11 } catch (err) { 12 console.error(err); 13 } 14} 15 16getCleanCodeArticle()

⬆ back to top

Error Handling

Thrown errors are a good thing! They mean the runtime has successfully

identified when something in your program has gone wrong and it's letting

you know by stopping function execution on the current stack, killing the

process (in Node), and notifying you in the console with a stack trace.

Don't ignore caught errors

Doing nothing with a caught error doesn't give you the ability to ever fix

or react to said error. Logging the error to the console (console.log)

isn't much better as often times it can get lost in a sea of things printed

to the console. If you wrap any bit of code in a try/catch it means you

think an error may occur there and therefore you should have a plan,

or create a code path, for when it occurs.

Bad:

javascript

1try { 2 functionThatMightThrow(); 3} catch (error) { 4 console.log(error); 5}

Good:

javascript

1try { 2 functionThatMightThrow(); 3} catch (error) { 4 // One option (more noisy than console.log): 5 console.error(error); 6 // Another option: 7 notifyUserOfError(error); 8 // Another option: 9 reportErrorToService(error); 10 // OR do all three! 11}

Don't ignore rejected promises

For the same reason you shouldn't ignore caught errors

from try/catch.

Bad:

javascript

1getdata() 2 .then(data => { 3 functionThatMightThrow(data); 4 }) 5 .catch(error => { 6 console.log(error); 7 });

Good:

javascript

1getdata() 2 .then(data => { 3 functionThatMightThrow(data); 4 }) 5 .catch(error => { 6 // One option (more noisy than console.log): 7 console.error(error); 8 // Another option: 9 notifyUserOfError(error); 10 // Another option: 11 reportErrorToService(error); 12 // OR do all three! 13 });

⬆ back to top

Formatting

Formatting is subjective. Like many rules herein, there is no hard and fast

rule that you must follow. The main point is DO NOT ARGUE over formatting.

There are tons of tools to automate this.

Use one! It's a waste of time and money for engineers to argue over formatting.

For things that don't fall under the purview of automatic formatting

(indentation, tabs vs. spaces, double vs. single quotes, etc.) look here

for some guidance.

Use consistent capitalization

JavaScript is untyped, so capitalization tells you a lot about your variables,

functions, etc. These rules are subjective, so your team can choose whatever

they want. The point is, no matter what you all choose, just be consistent.

Bad:

javascript

1const DAYS_IN_WEEK = 7; 2const daysInMonth = 30; 3 4const songs = ["Back In Black", "Stairway to Heaven", "Hey Jude"]; 5const Artists = ["ACDC", "Led Zeppelin", "The Beatles"]; 6 7function eraseDatabase() {} 8function restore_database() {} 9 10class animal {} 11class Alpaca {}

Good:

javascript

1const DAYS_IN_WEEK = 7; 2const DAYS_IN_MONTH = 30; 3 4const SONGS = ["Back In Black", "Stairway to Heaven", "Hey Jude"]; 5const ARTISTS = ["ACDC", "Led Zeppelin", "The Beatles"]; 6 7function eraseDatabase() {} 8function restoreDatabase() {} 9 10class Animal {} 11class Alpaca {}

⬆ back to top

Function callers and callees should be close

If a function calls another, keep those functions vertically close in the source

file. Ideally, keep the caller right above the callee. We tend to read code from

top-to-bottom, like a newspaper. Because of this, make your code read that way.

Bad:

javascript

1class PerformanceReview { 2 constructor(employee) { 3 this.employee = employee; 4 } 5 6 lookupPeers() { 7 return db.lookup(this.employee, "peers"); 8 } 9 10 lookupManager() { 11 return db.lookup(this.employee, "manager"); 12 } 13 14 getPeerReviews() { 15 const peers = this.lookupPeers(); 16 // ... 17 } 18 19 perfReview() { 20 this.getPeerReviews(); 21 this.getManagerReview(); 22 this.getSelfReview(); 23 } 24 25 getManagerReview() { 26 const manager = this.lookupManager(); 27 } 28 29 getSelfReview() { 30 // ... 31 } 32} 33 34const review = new PerformanceReview(employee); 35review.perfReview();

Good:

javascript

1class PerformanceReview { 2 constructor(employee) { 3 this.employee = employee; 4 } 5 6 perfReview() { 7 this.getPeerReviews(); 8 this.getManagerReview(); 9 this.getSelfReview(); 10 } 11 12 getPeerReviews() { 13 const peers = this.lookupPeers(); 14 // ... 15 } 16 17 lookupPeers() { 18 return db.lookup(this.employee, "peers"); 19 } 20 21 getManagerReview() { 22 const manager = this.lookupManager(); 23 } 24 25 lookupManager() { 26 return db.lookup(this.employee, "manager"); 27 } 28 29 getSelfReview() { 30 // ... 31 } 32} 33 34const review = new PerformanceReview(employee); 35review.perfReview();

⬆ back to top

Comments

Only comment things that have business logic complexity.

Comments are an apology, not a requirement. Good code _mostly_ documents itself.

Bad:

javascript

1function hashIt(data) { 2 // The hash 3 let hash = 0; 4 5 // Length of string 6 const length = data.length; 7 8 // Loop through every character in data 9 for (let i = 0; i < length; i++) { 10 // Get character code. 11 const char = data.charCodeAt(i); 12 // Make the hash 13 hash = (hash << 5) - hash + char; 14 // Convert to 32-bit integer 15 hash &= hash; 16 } 17}

Good:

javascript

1function hashIt(data) { 2 let hash = 0; 3 const length = data.length; 4 5 for (let i = 0; i < length; i++) { 6 const char = data.charCodeAt(i); 7 hash = (hash << 5) - hash + char; 8 9 // Convert to 32-bit integer 10 hash &= hash; 11 } 12}

⬆ back to top

Don't leave commented out code in your codebase

Version control exists for a reason. Leave old code in your history.

Bad:

javascript

1doStuff(); 2// doOtherStuff(); 3// doSomeMoreStuff(); 4// doSoMuchStuff();

Good:

javascript

1doStuff();

⬆ back to top

Don't have journal comments

Remember, use version control! There's no need for dead code, commented code,

and especially journal comments. Use git log to get history!

Bad:

javascript

1/** 2 * 2016-12-20: Removed monads, didn't understand them (RM) 3 * 2016-10-01: Improved using special monads (JP) 4 * 2016-02-03: Removed type-checking (LI) 5 * 2015-03-14: Added combine with type-checking (JR) 6 */ 7function combine(a, b) { 8 return a + b; 9}

Good:

javascript

1function combine(a, b) { 2 return a + b; 3}

⬆ back to top

Avoid positional markers

They usually just add noise. Let the functions and variable names along with the

proper indentation and formatting give the visual structure to your code.

Bad:

javascript

1//////////////////////////////////////////////////////////////////////////////// 2// Scope Model Instantiation 3//////////////////////////////////////////////////////////////////////////////// 4$scope.model = { 5 menu: "foo", 6 nav: "bar" 7}; 8 9//////////////////////////////////////////////////////////////////////////////// 10// Action setup 11//////////////////////////////////////////////////////////////////////////////// 12const actions = function() { 13 // ... 14};

Good:

javascript

1$scope.model = { 2 menu: "foo", 3 nav: "bar" 4}; 5 6const actions = function() { 7 // ... 8};

⬆ back to top

Translation

This is also available in other languages:

Armenian: hanumanum/clean-code-javascript/

Bangla(বাংলা): InsomniacSabbir/clean-code-javascript/

Brazilian Portuguese: fesnt/clean-code-javascript

Simplified Chinese:

alivebao/clean-code-js

beginor/clean-code-javascript

Traditional Chinese: AllJointTW/clean-code-javascript

French: eugene-augier/clean-code-javascript-fr

German: marcbruederlin/clean-code-javascript

Indonesia: andirkh/clean-code-javascript/

Italian: frappacchio/clean-code-javascript/

Japanese: mitsuruog/clean-code-javascript/

Korean: qkraudghgh/clean-code-javascript-ko

Polish: greg-dev/clean-code-javascript-pl

Russian:

BoryaMogila/clean-code-javascript-ru/

maksugr/clean-code-javascript

Spanish: tureey/clean-code-javascript

Spanish: andersontr15/clean-code-javascript

Serbian: doskovicmilos/clean-code-javascript/

Turkish: bsonmez/clean-code-javascript

Ukrainian: mindfr1k/clean-code-javascript-ua

Vietnamese: hienvd/clean-code-javascript/

Persian: hamettio/clean-code-javascript

⬆ back to top

On this page