CHAPTER 15 Ensuring Correct Implementation of Chainable Methods


  • Using chainable methods to create more elegant code
  • Using test-driven development to implement chainable methods
  • Writing DRY unit tests to verify that methods are chainable
  • Showing how the then method of ECMAScript 6 promises enables chaining


The code downloads for this chapter are found at on the Download Code tab. The files are in the Chapter 15 download and individually named according to the filenames noted throughout this chapter.

Does the structure and syntax of the following JavaScript statement look familiar?

$;("#myDiv").text("JavaScript").removeClass("unreliable") .addClass("reliable");

If you’ve done any client-side development since 2008 or so, chances are the answer is “Yes.” The statement is written using jQuery, a popular client-side JavaScript framework that’s used by over 52 million websites on the Internet according to in March 2015.

The jQuery code sample illustrates the use of chainable methods: functions constructed so they can be invoked one after another on the same object in a single statement.

You don’t have to look far for other uses of chainable methods in JavaScript. You may have recognized that the then method of the Promise API used throughout the book is chainable.

Get Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.