Chapter 7. Meta Programming

Meta programming is programming where the operation targets the behavior of the program itself. In other words, it’s programming the programming of your program. Yeah, a mouthful, huh?

For example, if you probe the relationship between one object a and another b—are they [[Prototype]] linked?—using a.isPrototype(b), this is commonly referred to as introspection, a form of meta programming. Macros (which don’t exist in JS, yet)—where the code modifies itself at compile time—are another obvious example of meta programming. Enumerating the keys of an object with a for..in loop, or checking if an object is an instance of a “class constructor,” are other common meta programming tasks.

Meta programming focuses on one or more of the following: code inspecting itself, code modifying itself, or code modifying default language behavior so other code is affected.

The goal of meta programming is to leverage the language’s own intrinsic capabilities to make the rest of your code more descriptive, expressive, and/or flexible. Because of the meta nature of meta programming, it’s somewhat difficult to put a more precise definition on it than that. The best way to understand meta programming is to see it through examples.

ES6 adds several new forms/features for meta programming on top of what JS already had.

Function Names

There are cases where your code may want to introspect on itself and ask what the name of some function is. If you ask what a function’s name is, ...

Get You Don't Know JS: ES6 & Beyond 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.