In Chapter 1 , we discussed refactoring as a process of changing code safely and without changing behavior in order to improve quality. In Chapter 2 we looked at the complexity of the JavaScript ecosystem and the consequent difficulty in pinning down what style and quality mean for us. In Chapters 3 and 4 , we laid the groundwork for testing, which is the easiest way to have confidence in our code, and a prerequisite to changing code safely (aka refactoring).

In this chapter, we finally turn to the specific relationship between refactoring and quality. The previous chapter included a diagram ( Figure 4-1 , reproduced as Figure 5-1 ) that described the relationship between testing and refactoring. Consider the main three questions in the diagram:

  • What’s the situation?
  • Do you have enough coverage?
  • Is the code bad?

The first question should hopefully be very easy to answer. The second one can be addressed by a coverage tool that runs with your test suite and outputs places that are specifically missing coverage. There are times when coverage tools may miss complex cases, though, so a line of code being covered does not necessarily mean we are confident in it. Achieving code quality through the process of refactoring is absolutely dependent on confidence.

In this chapter, we’re developing a strategy to answer the third question: is the code bad?

Figure 5-1. Testing and refactoring flow chart

Due to JavaScript’s multiparadigmatic nature, answering this question is not always easy. Even without using specialized libraries, we can strive to (or be forced to) make our code follow a few styles: object-oriented (prototypal or class-based), functional, or asynchronous (with promises or callbacks).

Before we address what refactoring in those styles entails, we must deal with a paradigm that the worst codebases tend to employ: unstructured imperative programming . If those italics didn’t scare you, perhaps a description of this type of codebase in a frontend context will. Time for a spooky JavaScript story:

The JavaScript in the file, called main.js , runs on page load. It’s about 2,000 lines. There are some functions declared, mostly attached to an object like $ so that jQuery will do its magic. Others are declared with function _whatever_ (){} so that they are in the global scope. Objects, arrays, and other variables are created as needed along the way, and freely changed throughout the file. A half-hearted attempt at Backbone, React, or some other framework was made at one point for a few crucial and complicated features. Those parts break often, as the team member who was initially excited about that framework has moved on to a startup that builds IoT litter boxes. The code is also heavily dependent on inline JavaScript inside of index.html .

Although frameworks can help to make this type of code less likely, they cannot and should not completely prevent the possibility of free-form JavaScript. However, this type of JavaScript is not inevitable, nor is it impossible to fix. The absolute first order of business is to understand functions, and not any of the fancy kinds. In this chapter, we will be exploring six basic components of functions:

  • Bulk (lines of code and code paths)
  • Inputs
  • Outputs (return values)
  • Side effects
  • this : the implicit input
  • Privacy
“JavaScript Jenga”

If the frontend JavaScript codebase spooky story didn’t resonate with you, perhaps a description of what working with one is like will sound more familiar.

Programmers are tasked with making changes to the frontend. Each time they do, they make as small a change as possible, adding a bit of code and maybe some duplication. There is no test suite to run, so in lieu of confidence, the tools they have available to ensure the quality of the codebase are 1) performing as many manual checks of critical functionality as is allowed by time and patience, and 2) hope. The codebase gets larger and a bit more unstable with every change.

Occasionally, a critical bug sneaks in, and the whole stack of blocks topples over, right in front of a user of the site. The only saving grace about this system is that version control allows the unstable (but mostly okay...probably?) previous version of the blocks to be set up without too much trouble.

This is technical debt in action. This is JavaScript Jenga.

Throughout the rest of this chapter, we will be using a tool for diagramming JavaScript called Trellus. All the diagrams in this chapter were generated with it, and you can diagram your own functions at trell.us .

Here’s how it starts: functions are just a circle ( Figure 5-2 ).

Figure 5-2. Just a circle

Simple enough. We’ll be adding parts to represent the following:

  • Bulk
  • Inputs
  • Outputs (return values)
  • Side effects
  • Context
  • Privacy

Before the chapter is through, we will have explored all of these components through this diagramming technique, making note of qualitative differences between them along the way.

Function Bulk

We use the term bulk to describe function bodies. It refers to two different but related characteristics:

  • Complexity
  • Lines of code

JavaScript linters (described in Chapter 3 ) pick up on both of these things. So if you’re using one as part of a build process (or preferably within your editor), you should see warnings for both if they become excessive.

There are no strict rules on bulk. Some teams like functions to be 25 or fewer lines of code. For others, 10 or fewer is the rule. As for complexity (aka cyclomatic complexity ), or “the number of code paths you should be testing,” the upper limit tends to be around six. By “code path” or “branch of code,” we mean one possible flow of execution. Branches of code can be created in a few ways, but the simplest way is through if statements. For example:

if(someCondition){
  // branch 1
} else {
  // branch 2
};

function(error){
  if(error){
    return error; // branch 1
  };
  // branch 2
};

Too much of one type of bulk will probably indicate the other type. A 100-line function probably has too many potential code paths as well. Similarly, a function with several switch statements and variable assignments will probably have a bulky line count too.

The problem with bulk is that it makes the code harder to understand and harder to test. The resulting lack of confidence is the exact scenario that leads to JavaScript Jenga.

In Defense of Bulk

Although classical refactoring techniques and trends in composable structures within frameworks and JavaScript packages point toward small functions (as well as objects and “components”) being a preferable approach, there are detractors.

No one is rushing to defend 200-line functions on principle, but you may occasionally encounter some who are critical of “tiny functions that don’t do anything but tell some other function to do something,” which makes the logic “hard to follow.”

This is tricky. Although following logic from function to function takes some patience and practice when compared to reading straight through a function, ideally there is less context to keep in your head and testing small functions is way easier.

All that said, after testing, being able to extract new functions and reduce bulk in extant ones is the most important skill to learn for refactoring. In doing so, however, you must make the higher-level code with consideration of the interface’s ability to hide its implementation appropriately. That demands naming things well, and having sensible inputs/outputs.

If every function was named some variant of passResultOfDataToNextFunction , then extracting functions would only scatter the implementation, meaning the bulk would be preferable.

This book argues against bulk, but in your team, you might have to put up with a bit more bulk than what your preference may be. Be aware that reducing bulk, as with any refactoring target, may be met with objections on the grounds of both stylistic preferences and its (real or perceived) importance with respect to other development objectives.

Although it’s a less common shape for bad code to take, if you find that your code goes too far in delegating functions for your comfort, just inline the functions. It’s not hard to do:

function outer(x, y){
  return inner(x, y);
};
function inner(x, y){
  // setup
  return // something with x and y
};

You have a few choices here. If outer is the only thing calling inner , you could just move the function body from inner into outer , keeping in mind that you’d need:

function outer(x, y){
  // setup 
  return // something with x and y
};

Or if the // setup part is complex enough, and there are a lot of calls to inner that don’t come from outer , you might want to delete outer , change any calls from outer to inner , and, as necessary, negate or adjust the // setup you used for inner .

If you find yourself confused by inner functions, inlining them and then extracting new ones is a great way to explore the code. As always, have tests in place, and be ready to roll back to an earlier version.

Let’s add a few pieces to our diagram to help us represent bulk, and while we’re at it, we’ll give our functions names. We simply have a box that states the function name and the number of lines that the function has. To represent the paths of code in (complexity in) our function, we can add pie slices. The darker shaded slices are tested, and the lighter ones are untested. Figures 5-3 and 5-4 are two examples.

Figure 5-3 has two code paths and seven lines of code. One of the code paths is tested (dark) and one is not (light).

Figure 5-3. 7 lines, with one out of two code paths tested

Figure 5-4 is bulkier, with 45 lines of code and 8 code paths (pie slices). But because all of the pie slices are dark, we know that each of the eight code paths is tested. 

Figure 5-4. 45 lines with eight code paths, all tested

Inputs

For our purposes, we will consider three types of inputs to a function: explicit, implicit, and nonlocal. In the following function, we would say a and b are explicit inputs (aka explicit parameters or formal parameters ), because these inputs are part of the function definition:

function add(a, b){
  return a + b;
};

Incidentally, if we call add(2, 3) later on, 2 and 3 are “actual parameters,” “actual arguments,” or just “arguments” because   they are used in the function call , as opposed to “formal parameters,” which occur in the function definition . People mix up the arguments versus parameters thing all the time, so don’t worry too much about it if you mix them up too. The main thing is that what we’re calling “explicit parameters” appear inside of the function definition (see Figure 5-5 ).

Figure 5-5. An add function with two explicit parameters

Note that we are describing the type of the inputs ( number ), rather than specific values or references to the formal parameters of the function signature ( a and b ). Since JavaScript doesn’t care what types we pass in, our names will also not necessarily map to specific types of primitives or objects that we’re passing.

Although we’re not diving deeply into objects here, the implicit input or implicit parameter in the following addTwo function is the calculator object within which the function is defined (see Figure 5-6 ):

var calculator = {
  add: function(a, b){
    return a + b;
  },
  addTwo: function(a){
    return this.add(a, this.two);
  },
  two: 2
};

Figure 5-6. addTwo function with explicit input (number) and implicit input (calculator)

In JavaScript the implicit parameter is referred to by this . You may have seen it as self in other languages. Keeping track of this is probably the most confusing thing in JavaScript, and we’ll talk about it a bit more in “Context Part 1: The Implicit Input” .

The third type of inputs, nonlocal inputs (commonly known as “free variables”), can be especially tricky, especially in their ultimate form, the dreaded global variable. Here’s an innocent-looking example (see Figure 5-7 ):

var name = "Max";
var punctuation = "!";
function sayHi(){
  return "Hi " + name + punctuation;
};

Figure 5-7. The sayHi function has two nonlocal inputs: name and punctuation

Is it so innocent, though? name and punctuation can be redefined, and the function can still be called at any point. The function has no opinion or guard against that. It may not jump out as a problem in these 5 lines, but when a file is 200 or 300 lines long, variables floating around like this make life more difficult, as they could change at any point.

“name” is not a great name

Although it’s not perfectly supported across all implementations, name happens to be a property of function objects for many contexts. When in doubt, avoid it.

In testing, figuring out what inputs you need to set up can take more time than any other task involved. When explicit inputs are complex objects, this can be difficult enough (although it can be helped by factories and fixtures, as discussed in Chapter 3 ), but if your function relies heavily on implicit input (or worse, nonlocal/global inputs), then you have that much more setup to do. Implicit state (using this ) isn’t as bad as nonlocal input. Actually, object-oriented programming (OOP) relies on using it intelligently.

The recommendation here is to have your functions, as much as possible, rely on explicit inputs (which hints at functional programming, or FP, style), followed by implicit inputs (aka this , which hints at OOP style), followed in a distant third by nonlocal/global state. An easy way to guard against nonlocal state is to wrap as much of the code as possible in modules, functions, and classes (which, yes, are actually functions in disguise).

Note that even when state is explicit, JavaScript allows a wide range of flexibility in how parameters are passed. In some languages, formal parameters (the parts of a function definition that specify explicit inputs) require the types ( int , boolean , MyCoolClass , etc.) to be specified as well as the parameter name. There is no such restriction in JavaScript. This leads to some convenient possibilities. Consider the following :

function trueForTruthyThings(sometimesTruthyThing){
  return !!(sometimesTruthyThing);
};

When calling this function, we could pass in a parameter of any type we wanted. It could be a boolean, an array, an object, or any other type of variable. All that matters is that we can use the variable inside of the function. This is a very flexible approach, which can be handy, but can also make it difficult to know what types of parameters are required in order to exercise a function under test.

JavaScript offers two additional approaches that increase flexibility even further. The first is that the number of formal parameters doesn’t have to correspond with the number passed into the function call. Take a function like:

function add(a, b){
  return a + b;
};

This will happily return 5 if you call it as add(2, 3) , but also if you call it as add(2, 3, 4) . The formal parameters don’t care what you pass in; only the function body does. You can even supply fewer arguments, as in this: add(2) . This will return NaN (“Not a Number”) because 2 is being added to undefined , although in Chapter 11 , we’ll explore a technique called currying that makes it useful to supply fewer arguments than specified by the formal parameters.

As for extra arguments supplied to a function call, it is possible to recover and use them in the function body, but this functionality should be used cautiously, as it complicates a testing procedure that benefits from simple inputs and less bulk in the function body.

One last trick that the formal parameters can play in JavaScript is allowing not just simple types but also objects and functions as parameters. Sometimes this extreme amount of flexibility can be useful, but consider the following case:

function doesSomething(options){
  if(options.a){
    var a = options.a;
  }
  if(options.b){
    var b = options.b;
  }
  ...
}

If you have a mystery object or function that is passed in at runtime, you have potentially bloated your test cases without realizing how. When you hide the values needed inside of an object with a generic name like params or options , your function body should hopefully supply guidance on how those values are used and clues about what they are. Even with clarity inside of the function body, though, it’s definitely preferable to use parameters with real names to keep the interface smaller and help to document the function right up top.

There is nothing wrong with passing a whole object to a function rather than breaking it all into named individual parameters, but calling it params or options might hint that the function is doing too much. If the function does take a specific type of object, it should have a specific name. See more about renaming things in “Renaming Things” .

A bit about ECMAScript

We briefly discussed the ECMAScript (ES) specification in Chapter 2 as what to watch for updates to JavaScript (keeping in mind that libraries and implementations may either lag behind or actually be ahead of the curve). What we didn’t talk about is how ES naming conventions work. As a relatively new convention, the standards body dropped version numbers like “ES6” in favor of yearly releases like “ES2015” (which happens to correspond to ES6). The version that will be released next is described as “ESNext.” As of this writing, this convention hasn’t been in use for long, so don’t be shocked if this changes again in the future.

Prior to ES2015, passing an object to a function call offered the advantage of somewhat illustrating the function signature (what parameters are used) as opposed to having what could be just magic strings or numbers. Compare these two:

search('something', 20);
// vs.
search({query: 'something', pageSize: 20});

The first function definition would necessarily include explicitly named parameters. The second would likely have one parameter named, at best, searchOptions and at worst options . The first name ( searchOptions ) does not offer much more detail to document the call, but is at least potentially unique.

However, there is a way (thanks to ES2015) that you can have clarity in the calls and in the definitions:

function search({query: query, pageSize: pageSize}){
  console.log(query, pageSize);
};
search({query: 'something', pageSize: 20});

It’s a little awkward, but it allows you to be specific in both places and avoids the pitfalls of sending the wrong types of arguments or mindlessly passing a params object through to another function call (maybe after some manipulations first). Honestly, that second pattern is so bad and rampant that this somewhat-awkward construct still looks pretty great by comparison. If you’re curious about the feature that makes this work, it’s called destructuring , and there’s a lot to it. It’s for assignments in general (not just params ), and you can use it with arrays as well as objects.  

If you throw using a function as a parameter (a callback ) into the mix, then you could be adding significantly more bulk. Every function call now has the potential to require any number of new test cases to support it.

Sad Paths

We discussed earlier how coverage does not necessarily equate to confidence. Sad paths are one particular reason why. The problem might be a data integrity issue from a user interaction gone awry (e.g., an incorrectly formatted form entry step that allows bad data to get into the database).

Even if your code tests each branch of an if-else clause inside your function, some inputs will cause problems. This includes not just unexpected parameters passed to the function, but also nonlocal inputs such as what time or date it is, as well as random numbers.

In languages with strict type checking systems (unlike JavaScript), a good number of these sad paths go away. Yet automated coverage tools will not help you here. Sad paths will likely be hidden in the code (and test cases) that you didn’t write.

Mutation testing, as described in Chapter 3 , can be of some help here. But considering that there are potentially infinite error-causing inputs to your functions in JavaScript (and the more flexibility you insist on, the more likely you are to hit one), the best defense against sad paths is to ensure your inputs will be evaluated correctly by your function ahead of time. Otherwise, you’re stuck with seeing the bug happen live, and then writing a regression test and code to handle it.

Note that because of input validation (or using more robust mechanisms inside of a function), a sad path will not necessarily mean a new path of code that would require a new pie slice in our diagramming method.

Passing in functions as inputs to a function can be done in a rational way, but not recognizing the trade-offs between simplicity in testing and flexibility is a mistake.

The overall recommendation for this section is to have simple and explicit inputs whenever possible, both in the function definitions and calls. This makes testing a great deal easier.

Here are a few recommendations to wrap up our discussion on inputs:

  • Overall, the fewer inputs you have, the easier it will be to keep bulk under control and test your code.
  • The fewer nonlocal inputs you have, the easier your code will be to understand and test.
  • Every function has a this as an implicit input; however, this may be unused, or even undefined in a lot of cases. If this is unused, feel free not to add the thisType ~> part of the diagram.
  • Most of all, explicit inputs are more reliable than this or nonlocal inputs.

Outputs

By output, we mean the value that is returned from a function. In our ideal style, we always want to return something. There are cases where this is hard or not true (some asynchronous styles and procedural, side effect–driven code), but we’ll deal with asynchronous code in Chapter 10 and discuss side effects later in this chapter (as well as in Chapter 11 ).

One of the most common mistakes you will see in a function is ignoring the output by not returning anything:

function add(a, b){
  a + b;
};

In this case, it’s pretty clear that the return keyword has been omitted, which means this function will simply return undefined ( Figure 5-8 ). This can be easy to miss, for two reasons. First of all, not all languages are the same. Rubyists (a lot of whom write JavaScript as their second language) will sometimes forget the return statement because the last line in a Ruby function is returned implicitly.

Secondly, if the style of most of the codebase consists of side effects (covered next), then the return value is less important than that effect. This is especially common in jQuery-supported codebases where almost every line is a click handler that runs a callback (which is often fancy side effect code). Programmers used to side effect–based code will also tend to fail to return anything.

Figure 5-8. This add function doesn’t specify a return value, so it defaults to undefined

Void functions

If no value is explicitly returned in JavaScript (using the return keyword), undefined will be returned. Since this provides little to no information about what the function did, even in the traditional case of using a void function for side effect–producing functions, there is likely some information of value produced by the side effect—even if it is just the result or simply the success of the side effect—that it would be preferable to return. When the side effect specifically changes the context ( this ), returning this is also a viable option.

It is recommended that you return real values when possible rather than explicitly returning undefined / null or implicitly returning undefined .

This function, however, does return something (see Figure 5-9 ):

function add(a, b){
  return a + b;
};

Figure 5-9. An add function that returns a number

Generally speaking, we want a decent return value (not null or undefined ), and we want the types from various code paths to match—returning a string sometimes and a number other times means you will probably have a few if-else statements in your future.  Returning an array with mixed types can be similarly awkward when compared with returning a simple value or an array of like types.

Strongly typed languages

Some languages have mechanisms to prescribe that return values (and inputs) be of a particular type (or explicitly return nothing). Having seen how JavaScript handles inputs, we should not be surprised to find a similar flexibility for return values.

We’ll get into this more in Chapter 11 .

The recommended approach to output values is to, whenever possible, return a consistent and simple value, and avoid that value being null or undefined . With functions that cause destructive actions (like altering an array or changing the DOM), it can be nice to return an object that describes what effect took place. Sometimes that just means returning this . Returning something informative, even when nothing was explicitly asked for, is a good habit, and helps in testing and debugging.

One additional complication for outputs is functions that return different types. Consider this function:

function moreThanThree(number){
  if(number > 3){
    return true;
  } else {
    return "No. The number was only " + number + ".";
  }
};

This function returns either a boolean or a string (see Figure 5-10 ). This isn’t great because code that calls this function will likely have its own conditionals to check for which type was returned.

Figure 5-10. This function could return a boolean or a string

As is the theme so far for this chapter, simpler is better when it comes to outputs (return types). Returning different types of values can complicate the code. Additionally, we want to avoid returning a null or undefined , as a better solution is likely available. Finally, we should strive to return values that are of the same type (or types implementing interfaces that won’t require a conditional check after or around the function call), regardless of which value is returned.

Side Effects

Some languages find side effects to be so dangerous that they make it very difficult to introduce them. JavaScript doesn’t mind the danger at all. As it is used in practice, one of jQuery’s main jobs (if not its primary responsibility) is to manipulate the DOM, and this happens through side effects.

The good part about side effects is that they are usually directly responsible for all the work anyone cares about. Side effects update the DOM. Side effects update values in the database. Side effects make console.log happen.

Despite all that side effects make possible, our goal is to isolate them and limit their scope. Why? There are two reasons. One is that functions with side effects are harder to test. The other is that they necessarily have some effect on (and/or rely on) state that complicates our design.

We will discuss side effects much more in Chapter 11 , but for now, let’s update our symbolic diagramming of side effects. Here is a simple example (see Figure 5-11 ):

function printValue(value){
  console.log(value);
};

Figure 5-11. A function with a very common side effect: logging

Notice that because this function does not return anything, the return value is undefined .

Ideally, the fewer side effects the better, and where they must exist, they should be isolated if possible. One update to some well-defined interface (say, a single database row) is easier to test than multiple updates to it, or to multiple database rows.

Context Part 1: The Implicit Input

In explaining inputs and outputs, we skimmed over something somewhat complex but very important, which we will cover now: the “implicit input,” which appears on the left of the diagrams as _someThisValue_ ~> (see e.g., Figure 5-6 ). someThisValue is the this that we’ve been talking about so far.

So what is this ?

Depending on your environment, outside of any other context, this could refer to a base object particular to the environment. Try typing this (and pressing Enter) in a browser’s interpreter (console). You should get back the window object that provides the kinds of functions and subobjects you might expect, such as console.log . In a node shell, typing this will yield a different type of base object, with a similar purpose. So in those contexts, typing any of these things will give you 'blah' .

console.log('blah');
this.console.log('blah');
window.console.log('blah'); // in a browser
global.console.log('blah'); // in a node shell

Interestingly enough, if you save a node file and run it, this prints as an empty object, {} , but global works as in the node shell and global objects like console are still available to use. Although this.console.log won’t work in a node file that you run, global.console.log will. That is related to how the node module system works. It’s a bit complicated, but know that the top-level scope in most environments is also this , but in node, it’s the module scope. Either way, it’s fine, because most of the time you don’t want to define functions or variables in the global namespace anyway.

In any case, we can expect our this to be the top-level scope when we check it inside of functions declared in the top-level scope:

var x = function(){
  console.log(this);
}
x(); // here, we'll see our global object, even in node files

So, that is top-level scope in a nutshell. Let’s diagram this last code listing with its implicit input ( Figure 5-12 ).

Figure 5-12. This function has the global object as its “this” value

this in Strict Mode

When you’re in strict mode, this will behave differently. For this code:

var x = function(){
  'use strict'
  console.log(this);
}
x();

undefined will be logged. In strict mode, not every function has a this . If you create this script and run it with node:

'use strict'
var x = function(){
  console.log(this);
}
x();

You will see the result ( this is undefined ). However, typing this second code snippet line by line in a node REPL (just type **node** at the terminal) or in a browser console will not apply strict mode to x , and the global object will be returned.

The Trellus function diagram for x in the first snippet looks like Figure 5-13 .

Figure 5-13. A function with a this value of undefined

Now the function is four lines long and still returns undefined as it did before. The side effect (which now logs undefined instead of the global object) is still present. The most crucial difference is that this no longer attaches to any this object other than undefined .

Whether you’re writing a node module or any decently sized program on the frontend, you’ll generally want only one or a small handful of variables to be scoped inside of the top-level scope (something has to be defined there, or you wouldn’t be able to access anything from the outermost context).

One way to create a new context is by using a simple object like this:

var anObject = {
  number: 5,
  getNumber: function(){ return this.number }
}

console.log(anObject.getNumber());

Here, this is not the global object, but anObject . There are other ways to set a context, but this is the simplest. By the way, because you’re creating a literal object with the {} syntax, this is called an object literal .

Keeping in mind that we’re diagramming functions, not objects, let’s see what our getNumber function looks like ( Figure 5-14 ).

Figure 5-14. getNumber attached to a this of anObject

We have a few more ways to write code that will follow the diagram as well as the interface. First is the Object.create pattern:

var anObject =
    Object.create(null, {"number": {value: 5},
    "getNumber": {value: function(){return this.number}}});
console.log(anObject.getNumber());

Next is how you would attach getNumber to anObject using classes:

class AnObject{
  constructor(){
    this.number = 5;
    this.getNumber = function(){return this.number}
  }
}
anObject = new AnObject;
console.log(anObject.getNumber());
Some People Really, Really Hate Classes

Pretty much everyone likes object literals. Some people like Object.create . Some people like classes. Some people like writing constructor functions that behave a lot like classes, without all of the “syntactic sugar.”

Some objections to classes are are based on them obscuring the purity and power of JavaScript’s prototypal system...but on the other hand, a typical demonstration of this power and flexibility is the creation of an awkward, ad hoc class system.

Other objections to classes are based around inheritance being worse than delegation and/or composition, which is valid, although fairly unrelated to the use of just the class keyword.

If you are using the new keyword, whether from a class or a constructor function, this will be attached to a new object that is returned by the call to new .

In an OOP approach, you might find yourself using objects for simple things and object-producing classes, factory functions, and so on for more complex things, whereas in the FP style, you will probably find yourself using fewer classes.

JavaScript doesn’t seem to care how you write it. Perhaps you’ll find FP style to be more maintainable, but a given project or team could have a significant investment in an OOP style.

Your this can also change through use of the call , apply , and bind functions. call and apply are used in exactly the same way if you’re not passing any explicit inputs to the function. bind is like call or apply , but for saving the function (with the bound this ) for later use:

var anObject = {
  number: 5
}
var anotherObject = {
  getNumber: function(){ return this.number }
}
console.log(anotherObject.getNumber.call(anObject));
console.log(anotherObject.getNumber.apply(anObject));
var callForTheFirstObject = anotherObject.getNumber.bind(anObject);
console.log(callForTheFirstObject());

Note that neither object has both the number and the function. They need each other. Since we’re using bind , call , or apply , our diagram actually doesn’t have to change. As we are using it, this still refers to anObject , even though the function is defined on anotherObject ( Figure 5-15 ).

Figure 5-15. Nothing is actually changed here: getNumber still has anObject as its “this”

What’s new here is that, although the function lives in anotherObject , bind , call , and apply are used to assign the “implicit” input ( this ) in an “explicit” way to anObject .

You might be confused about why Figure 5-15 has anObject as its implicit parameter, even though the function is defined inside of anotherObject . It is because we’re diagramming the function calls that are like this:

anotherObject.getNumber.call(anObject);

We’re diagramming from the perspective of a function. We could also diagram the following function call:

anotherObject.getNumber();

And then anotherObject would be the implicit parameter (the this ), but its return type would be undefined , not number .

Let’s look at one more example:

var anObject = {
  number: 5
}
var anotherObject = {
  getIt: function(){ return this.number },
  setIt: function(value){ this.number = value; return this; }
}
console.log(anotherObject.setIt.call(anObject, 3));

Note that the setIt code returns its this value, so if you run this code, you will see the full anObject object with the updated value: { number: 3 } . This is what return this in the setIt function does. Otherwise, we would have just the side effect (mutating the anObject ’s number ) and no clear confirmation of what happened. Returning this makes testing (manually or automatically) much easier than just returning undefined from side effect–causing methods.

Let’s look at the diagram for setIt as it is called by the call function ( Figure 5-16 ).

Figure 5-16. Has a side effect, but still returns something useful

Note that even though it is a side effect–producing method, we have returned something: specifically, our this from anotherObject . As described earlier, that can help to simplify verification and testing as compared with simply returning undefined .  Additionally, returning this opens us up to the possibility of having a fluent interface , which means we could chain functions like this:

object.setIt(3).setIt(4).setIt(5);

Fluent interfaces

Fluent interfaces can be useful for things like aggregating database query conditions or bundling up DOM manipulations (jQuery does this). You might also see this described as chaining functions . This is a common and useful pattern in both OOP and FP styles. In OOP, it tends to be a result of returning this , whereas in FP, it is commonly the result of map , which returns an object (or functor , actually) of the same type (for instance, arrays “map” to other arrays and promises “then” onto other promises).

In FP style (and in the wrapper OOP patterns), you’ll see more of this:

f(g(h()));

That might seem very awkward in comparison with fluent interfaces, but FP has great strategies for combining/composing functions. We’ll look at those more in Chapter 11 .

All this is to say: if you’re just returning undefined anyway, returning this instead will provide more information and better interfaces.

As far as context goes, that’s about as complicated as it gets without delving into prototypes (and the three or four things that means), inheritance, mixins, modules, constructors, factory functions, properties, descriptors, getters, and setters.

After this chapter, it’s all about better code through better interfaces . We won’t shy away from the topics in the previous paragraph, but we won’t make idols of any patterns either. This book is meant to explore many different ways to improve code.

Any coding style you fall in love with is bound to be someone else’s heresy. JavaScript presents many opportunities for both reactions.

Context Part 2: Privacy

The last topic in this chapter is that of “private” functions, and what that means in JavaScript. Scope is a broader topic of hiding and exposing behavior that we’ll explore through examples later on. For now, we are only concerned with the privacy of functions, because as we noted earlier, private functions have unique implications for testing .

Namely, some feel that private functions are “implementation details,” and thus do not require tests. If we accept that premise, then ideally we can hide most of our functionality in private functions and have less code exposed that we need to test. Fewer tests can mean less maintenance. Additionally, we can clearly separate our “public interface” from the rest of the code, which means anyone using our code can still benefit when learning or referencing a small part of it.

So how do we create private functions? Pretending we don’t know anything about objects for a minute, we could do this:

(function(){
  console.log('hi');
})();

or this:

(function(){
  (function(){
    console.log('hi');
  })();
})();

Here we have some anonymous functions. They are created, and then disappear. Any this we put inside will link back to the top-level context. Since they’re anonymous, all they can do is run when we tell them to. Even if we know the this for anonymous functions, we can’t run them (except right away or as a callback), because they don’t have a name and can’t be addressed. Incidentally, these are called immediately invoked function expressions (IIFEs), and we’ll talk about them more in Chapter 7 .

We’ll explore a few more useful types of private functions in a minute, but first we have a new piece to add to our diagrams (see Figure 5-17 ). The diagrams for both of the preceding functions are the same (except for the lines of code, which you might argue is five rather than three for the second one).

Figure 5-17. A “private” anonymous function

What’s new here is that we have a dark ring around the main circle to denote that this is a “private” function, and you may or may not want (or be able) to test it. Any pie slices would still be apparent in a function with more code paths, and as with public functions, the slices would be darkened when tested.

Another way to design private methods is through the revealing module pattern:

var diary = (function(){
  var key = 12345;
  var secrets = 'rosebud';

  function privateUnlock(keyAttempt){
    if(key===keyAttempt){
      console.log('unlocked');
      diary.open = true;
    }else{
      console.log('no');
    }
  };

  function privateTryLock(keyAttempt){
    privateUnlock(keyAttempt);
  };

  function privateRead(){
    if(this.open){
      console.log(secrets);
    }else{
      console.log('no');
    }
  };

  return {
    open: false,
    read: privateRead,
    tryLock: privateTryLock
  }

})();

// run with
diary.tryLock(12345);
diary.read();

Reading this from top to bottom is a mistake. At its core, this is just creating an object with three properties, and assigning it to diary . We happen to be surrounding it with an anonymous (and immediately executing) function, but that is just to create a context where we can hide things. The easiest way to read this function is to first look at the object that it returns. Otherwise, it’s fairly similar to the last example in that all we’re doing is wrapping some code with an anonymous function.

diary ’s first property is open , which is a boolean initially set to false . Then it has two other properties that map to function definitions provided previously. The interesting part is that we have some things hidden in here. Neither the key and secrets variables nor the privateUnlock function has any way to be accessed directly through diary .

One thing that may look strange is that in the “private” privateUnlock function, instead of this.open , we have diary.open . This is because when we are running privateUnlock via the privateTryLock function, we lose our this context. To be clear, this is diary inside of the privateTryLock function, but it is the global object inside of privateUnlock .

As Trellus diagrams, these functions would look like Figures 5-18 and 5-19 .

Figure 5-18. The read function of diary

Figure 5-19. The tryLock function of diary

The read function just points to privateRead , so we use that definition for our diagram. It takes no explicit parameters. Its this (the implicit parameter) is the diary object (that is returned from the anonymous function call). It returns undefined and calls console.log as a side effect. But what about secrets , the nonlocal input? It is tempting to think of secrets as part of the diary object , but it isn’t. It’s part of the scope within which the object returned by diary was created. Contrast secrets with this.open , which is an attribute of the diary object itself.

The tryLock function also just points to another function ( privateTryLock ), so we use that function definition. Like read , it has a nonlocal input, but this time it is a function ( privateUnlock ) rather than a simple value ( secrets ) as in read ’s case. As far as the return values and side effects, the function definition itself doesn’t indicate it, but we don’t have to work too hard to see what side effects it has. However, in keeping with what most code coverage tools would report, this function only has one code path, even though its side effects depend on two paths inside of privateUnlock . Note that the same single code path would also be indicated by the diagram in the case that those two code paths affected the return value rather than, or in addition to, the side effects.

Now let’s look at privateUnlock ( Figure 5-20 ).

Figure 5-20. The privateUnlock function of diary

This function’s diagram looks a lot like tryLock ’s. One major difference is that it has the dark circle wrapping its code paths. This indicates that we are considering it as a private function. We’ll discuss this a bit more, but for now, here is a working idea of “private” functions in JavaScript: in JavaScript, there isn’t really a good way to make private functions. Basically, you have variables and functions that are either in scope and addressable, or not.

Something else might have jumped out of the diagram as interesting. The diary object (that is used for diary.open ) is not the function’s this , nor is it an explicit input: it is a nonlocal input. The mechanism here is a bit tricky, but this should illustrate what’s happening:

function hi(){
  console.log(hello);
};
hi();

// ReferenceError: hello is not defined

var hello = "hi";
hi();
// logs "hi"

It seems weird that diary is in scope, and it might seem like it has something to do with the function it is declared inside of being assigned to diary :

var diary = (function(){
  // does everyone in here know about diary?

But actually it works just like the hi function. When privateUnlock is declared, it doesn’t know what diary is yet, but that doesn’t matter. Once diary is declared in the top-level scope, everything knows about it, including previously declared functions, which includes privateUnlock . This might still seem magical, but basically, you can declare nonlocal inputs to functions after those functions are declared . As long as the nonlocal inputs are in a scope that the function can access when the functions are called , you can still use them in the function declarations.

If that doesn’t sink in, it’s okay. We’re about to stop using diary in that function because it’s a little awkward (also, it is hardcoded and will break if we change the variable name).

It is tempting to just expose the privateUnlock function to the object (adding another attribute to the returned object), but we won’t be able to keep it “private” (out of a directly addressable scope) that way.

To get around the awkwardness of repeating a name as we are doing with diary , some people’s first instinct is to pass along this with a variable called that :

var diary = (function(){
  var key = 12345;
  var secrets = 'programming is just syntactic sugar for labor';

  function privateUnlock(keyAttempt, that){
    if(key===keyAttempt){
      console.log('unlocked');
      that.open = true;
    }else{
      console.log('no');
    }
  };

  function privateTryLock(keyAttempt){
    privateUnlock(keyAttempt, this);
  };

  function privateRead(){
    if(this.open){
      console.log(secrets);
    }else{
      console.log('no');
    }
  }

  return {
    open: false,
    read: privateRead,
    tryLock: privateTryLock
  }

})();

Let’s see what that does to our diagram for privateUnlock (see Figure 5-21 ).

Figure 5-21. With two explicit inputs

Nothing much has changed here. The only difference is that now we have two explicit inputs to the privateUnlock function and one nonlocal input, which is an improvement from before.

Isn’t console a nonlocal input?

In other words: shouldn’t it be listed on the right of the diagrams too?

When it is used within the function, yes, it does act as a nonlocal input. We’ve omitted it in these diagrams to simplify them, but by all means, when you’re writing your own functions, add entries for console and anything else that’s not this or passed in as an explicit parameter.

Also realize that we’re not adding nonlocal inputs for every global object and subobject that we’re not using. That would make the diagrams very noisy.

Alternatively, we can use one of our this -fixing functions: call , apply , or bind . For call , you would change privateUnlock and privateTryLock like this:

var diary = (function(){
  var key = 12345;
  var secrets = 'sitting for 8 hrs/day straight considered harmful';

  function privateUnlock(keyAttempt){
    if(key===keyAttempt){
      console.log('unlocked');
      this.open = true;
    }else{
      console.log('no');
    }
  };

  function privateTryLock(keyAttempt){
    privateUnlock.call(this, keyAttempt);
  };

  function privateRead(){
    if(this.open){
      console.log(secrets);
    }else{
      console.log('no');
    }
  }

  return {
    open: false,
    read: privateRead,
    tryLock: privateTryLock
  };

})();

And in the bind version our privateTryLock function would look like this:

  function privateTryLock(keyAttempt){
    var boundUnlock = privateUnlock.bind(this);
    boundUnlock(keyAttempt);
  };

Or we could inline that boundUnlock variable by calling the bound function right away:

  function privateTryLock(keyAttempt){
    privateUnlock.bind(this)(keyAttempt);
  };

which puts us back to being pretty similar to the call syntax.

In any case, our diagram for privateUnlock with the this -fixing in place shouldn’t be too shocking (see Figure 5-22 ).

Figure 5-22. One explicit parameter (number) and one implicit parameter (diary)

Now our function has an implicit input of diary . key is still stuck as a nonlocal. It, like secrets and privateUnlock , is there for anyone to grab up when the diary -creating anonymous function runs, but it’s not attached to any object (any this ) of significance.

Some variables (including functions) have a useful this that they are attached to. Others just have a scope where they are available and addressable.

Before leaving our diary example, there’s one important function that we’ve neglected to diagram: our diary -creating function ( Figure 5-23 ).

Figure 5-23. The diary-creating function is pretty simple

It’s actually what’s not in this diagram that is surprising. First of all, the function is anonymous. It is the result of calling the function that is assigned to a variable that happens to be called diary :

var diary = (function(){

Similarly, the return type is an object: {} . We could get specific and say it returns an object with particular properties, or we could say it’s a diary object. However, it’s worth highlighting that our function has no idea of what a diary is until after its result is assigned to the variable.

At this point, you might be wondering about classes. Maybe classes have some magical way to implement private methods? Nope. There have been proposals to ECMAScript petitioning for such things, but as of this writing, they’re still not a sure bet.

If we were really insistent on this behavior for classes, how might we write it?

class Diary {
  constructor(){
    this.open = false;
    this._key = 12345;
    this._secrets = 'the average human lives around 1000 months';
  };

  _unlock(keyAttempt){
    if(this._key===keyAttempt){
      console.log('unlocked');
      this.open = true;
    }else{
      console.log('no')
    }
  };
  tryLock(keyAttempt){
    this._unlock(keyAttempt);
  };

  read(){
    if(this.open){
      console.log(this._secrets);
    }else{
      console.log('no');
    }
  }
}
d = new Diary();
d.tryLock(12345);
d.read();

Now our private variables and _unlock function are exposed in the class. Also, we’ve prepended an underscore to indicate functions and variables that shouldn’t be accessed directly. If we consider our private/underscore function to be a private implementation detail and therefore to not require testing, we now have a visual cue to help us convey that to others and our future selves. On the other hand, in this form, our tests should be very easy to write because all of our private methods are still addressable.

However, if we genuinely wanted to not expose our “hidden” information, we’ve failed. Let’s take a step in what looks like the wrong direction:

var key = 12345;
var secrets = 'rectangles are popular with people, but not nature';
function globalUnlock(keyAttempt){
  if(key===keyAttempt){
    console.log('unlocked')
    this.open = true;
  }else{
    console.log('no')
  }
};

class Diary {
  constructor(){
    this.open = false;
  };
  tryLock(keyAttempt){
    globalUnlock.bind(this)(keyAttempt);
  };
  read(){
    if(this.open){
      console.log(secrets);
    }else{
      console.log('no')
    }
  }
};
d = new Diary();
d.tryLock(12345);
d.read();

Now our hidden information is outside of our class. In fact (assuming we’re at the top-level scope), we’ve created global variables! What good is that?

Well, this is actually very close to something great that solves our problem in a different way. Save the following as diary_module.js :

var key = 12345;
var secrets='how to win friends/influence people is for psychopaths';
function globalUnlock(keyAttempt){
  if(key===keyAttempt){
    console.log('unlocked')
    this.open = true;
  }else{
    console.log('no')
  }
};

module.exports = class Diary {
  constructor(){
    this.open = false;
  };

  tryLock(keyAttempt){
    globalUnlock.bind(this)(keyAttempt);
  };

  read(){
    if(this.open){
      console.log(secrets);
    }else{
      console.log('no')
    }
  }
}

The only line we’ve changed is:

module.exports = class Diary {

To make use of this, we’ll need another file (you can call it diary_reader.js ) to import the module. Here’s what that file looks like:

const Diary = require('./diary_module.js');
let d = new Diary();
d.tryLock(12345);
d.read();

In this file, between the Diary “class” or the “instance” d , we’re not able to see the key or read the diary secrets without it. Unfortunately, this also means that if we want to test it using a similar require mechanism, we’re stuck either going back to the prepended underscore technique, putting our private functions in their own modules somehow, or conditionally including them for tests (and excluding them otherwise).

Is There Privacy in JavaScript?

As of this writing, there is no real privacy in JavaScript. Things are either in scope, or they’re not. Unfortunately, having an object and simply declaring some attributes as public and others as private is not really possible. Because every attribute (every property of an object) has a “this” that it attaches to, for functions to be “private” in JavaScript, they are necessarily also inaccessible.

So, practically speaking, at this time we have two conventions to choose from. The first is to give up on that dream and let attributes attach to some other this , with an eye toward the subconventions of doing so in a wrapping anonymous function (à la the revealing module pattern), or allowing this to attach to the global this for modules that are exported. Because exporting is a whitelisting operation, only the functions we specify will be imported by other scripts. This is handy for having a smaller API, but does complicate testing somewhat.

The second (admittedly clunky) convention is to let our functions happily bind to the same this as public members, but give visual cues (prefixing the function name with an _ is the most common) to indicate when something is intended to be private.

So for now, the meaning of private is more or less up to you, as well as how you decide that which you term “private.”

However, there are proposals from TC39 (the committee that evaluates and determines JavaScript features) related to privacy that are in the works. These include:

In this book, we’re doing the same thing with these additions as we’re doing with the likely forthcoming async and await features: we’re mentioning them, but not going into detail. From the spec, this is the proposed new syntax as of this writing:

class Foo {
  #a;
  #b;
  #sum() { return #a + #b; }
  printSum() { console.log(#sum()); }
  constructor(a, b) { #a = a; #b = b; }
};

So, #a and #b are both private (nonfunction/method) “fields,” and #sum is a private “method.” These identifiers with a # would be unavailable outside of the class context block. Thus, a new foo instance of class Foo wouldn’t have traditional property-style access à la foo.#a (or maybe foo.a —we don’t know, and we’re assuming that wouldn’t work anyway), foo.#b , or foo.#sum() . However, foo.printSum() would be fine, since that’s not private. Beyond that, details are sketchy at the moment (e.g., does foo.#a throw an error? Can a and #a both be used as field names? Is there a workaround to access the private fields and methods for testing?).

“Methods” versus “functions”

Throughout this book, we mostly refer to JavaScript functions as being functions . For some people, that implies functions in the sense of explicit inputs and output, whereas a method is used to mean some procedure or “just a chunk of code” that is attached to an object.

In any case, even without all of the facts in, the proposals for private fields and methods have implications for the future of JS generally:

  • Classes are getting more features that make unique constructs and not just “syntactic sugar” for constructor functions.
  • JavaScript is doubling down on OOP. Functional programming might be the “future” of JavaScript, but OOP is at least also the future.
  • Choosing “your JavaScript” will likely again be proven to be a function of time. The JavaScript of five years ago is starting to look weird to modern eyes. It’s likely that trend will continue.
  • If there is no workaround provided by the _#privateFunction_ syntax, you might see people still preferring the __privateFunction_ underscore hack for backward compatibility and in cases where testing private functions is desired. 

Wrapping Up

In this chapter, we covered a lot of detail about how JavaScript works. We centered our conversation on functions, as they are the most important and complicated construct in JavaScript (in any paradigm worth pursuing).

But as the goal was to be prescriptive as well as descriptive, here are some takeaways worth repeating:

  • Try to keep bulk (complexity and lines of code) low.
  • Try to keep the total number of inputs low.
  • Prefer explicit inputs to nonlocal inputs.
  • Make choices between passing this explicitly versus binding it to the function call, rather than hardcoding object names as nonlocal inputs.
  • Prefer real, meaningful return values to side effects.
  • Keep side effects to a minimum or nonexistent.
  • Have a well-defined this when possible for functions and other variables (attributes) by making them part of classes (or at least objects) to cut down on nonlocal inputs and global variables.
  • In JavaScript, mechanisms for privacy necessarily impact access, which can complicate code, especially when it comes to testing.

You should find these ideas help to make your code (as well as the diagrams) simpler.

As a final note, the style that we used here is “ this -friendly” as compared with some other approaches. In particular, using objects that change their values conflicts with aspects of the functional style we’ll discuss in Chapter 11 . In object-oriented (class- or prototype-based) style, however, you will use this frequently.