7 Hooked on metaprogramming

 

This chapter covers

  • Applying cross-functional behavior with metaprogramming and reflection
  • Using symbols to create interoperability between different realms in your application
  • Augmenting JavaScript’s internals with symbols
  • Understanding the basics of the Proxy/Reflect APIs
  • Enhancing the execution of methods with decorators
  • Performing leaner error handling with the throw expressions proposal

A program's text is just one representation of the program. Programs are not text. . . . We need a different way to store and work with our programs.

—Sergey Dmitriev, president and co-founder of JetBrains

Imagine a company like Intel that builds CPU chips. To automate a lot of the repetitive tasks, the company programs robots to build chips—a task that we call programming. Then, to scale to higher industry demands, it programs factories that build robots that build chips—a task that we call metaprogramming.

I hope that by now, you’re hooked on JavaScript. I know I am. As a byproduct of all the topics we’ve covered throughout our journey, we’ve uncovered some interesting dualities. One of these dualities is “functions as data” (chapter 4): the idea of expressing an eventual value as an execution of some function. We took that concept to another level in chapter 6 with “modules as data,” referring to JavaScript’s nature of reifying a module as a bound object that you can pass around as data to other parts of your application.

7.1 Common uses of metaprogramming in JavaScript

7.2 JavaScript symbols

7.3 Symbol registries

7.3.1 Local registry

7.3.2 Global registry

7.4 Practical application of symbols

7.4.1 Hidden properties

7.4.2 Interoperability

7.4.3 Serialization

7.5 Well-known symbols

7.5.1 @@toStringTag

7.5.2 @@isConcatSpreadable