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:

  1. When someone looks at the function signature, it’s immediately clear what
    properties are being used.
  2. 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.
  3. Linters can warn you about unused properties, which would be impossible
    without destructuring.

Bad:

  1. function createMenu(title, body, buttonText, cancellable) {
  2. // ...
  3. }

Good:

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

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, they 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:

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

Good:

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

Function names should say what they do

Bad:

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

Good:

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

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:

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

Good:

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

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:

  1. function 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. render(data);
  12. });
  13. }
  14. function showManagerList(managers) {
  15. managers.forEach((manager) => {
  16. const expectedSalary = manager.calculateExpectedSalary();
  17. const experience = manager.getExperience();
  18. const portfolio = manager.getMBAProjects();
  19. const data = {
  20. expectedSalary,
  21. experience,
  22. portfolio
  23. };
  24. render(data);
  25. });
  26. }

Good:

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

Set default objects with Object.assign

Bad:

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

Good:

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

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:

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

Good:

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

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:

  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.
  3. let name = 'Ryan McDermott';
  4. function splitIntoFirstAndLastName() {
  5. name = name.split(' ');
  6. }
  7. splitIntoFirstAndLastName();
  8. console.log(name); // ['Ryan', 'McDermott'];

Good:

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

Avoid Side Effects (part 2)

In JavaScript, primitives are passed by value and objects/arrays are passed by
reference. In the case of objects and arrays, if your function makes a change
in a shopping cart array, for example, by adding an item to purchase,
then any other function that uses that cart array will be affected by this
addition. That may be great, however it can be bad too. 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 “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 it has a reference to a shopping
cart array that the addItemToCart function modified by adding an unwanted
item.

A great solution would be for the addItemToCart to always clone the cart,
edit it, and return the clone. This ensures that no other functions that are
holding onto a reference of the shopping cart will be affected by any changes.

Two caveats to mention to this approach:

  1. 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!

  2. 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:

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

Good:

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

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:

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

Good:

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

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:

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

Good:

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

Encapsulate conditionals

Bad:

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

Good:

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

Avoid negative conditionals

Bad:

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

Good:

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

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:

  1. class 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:

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

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:

  1. function 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:

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

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:

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

Good:

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

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:

  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.
  3. for (let i = 0, len = list.length; i < len; i++) {
  4. // ...
  5. }

Good:

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

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:

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

Good:

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