Chapter 13. Functions and the Power of Abstract Thinking

If JavaScript were a Broadway play, functions would be the glittering starlet: they would hog the spotlight and take the last bow to thunderous applause (and some boos, no doubt: you can’t please everyone). We covered the mechanics of functions in Chapter 6, but now we’re going to consider the ways functions can be used, and how they can transform your approach to solving problems.

The very concept of a function is chameleon-like: it takes on different aspects when viewed in different contexts. The first—and simplest—perspective on functions we’re going to consider is that of a code reuse vehicle.

Functions as Subroutines

The idea of subroutines is a very old one, a practical concession to managing complexity. Without subroutines, programming would be a very repetitive affair indeed. Subroutines simply package some bit of repetitive functionality, give it a name, and allow you to execute that bit of functionality at any time simply by referring to that name.

Note

Other names for a subroutine are procedure, routine, subprogram, macro, and the very bland and generic callable unit. Note that in JavaScript, we don’t actually use the word subroutine. We just call a function a function (or a method). We’re using the term subroutine here to emphasize this simple use of functions.

Very often, a subroutine is used to package an algorithm, which is simply an understood recipe for performing a given task. Let’s consider ...

Get Learning JavaScript, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.