CHAPTER TWO

eval and Domain-Specific Languages

eval is a language construct that takes a string and executes it as code.

This means that in a language with an eval construct, the code that is being executed can come not just from input files, but also from the running code itself.

There are several reasons why this is interesting and useful. In this chapter, I will explore the degree to which JavaScript’s eval can be used to create simple language-based abstractions.

What About “eval Is Evil”?

I know that some of my readers, at the mention of the word eval, are feeling the adrenaline shoot into their veins, and hearing the solemn voice of a certain bearded JavaScript evangelist boom in the back of their heads. “eval is evil!” this voice proclaims.

I’ve never found absolute moral judgments very applicable in engineering. But if you do, and don’t want to reevaluate your faith, feel free to skip this chapter.

Practically speaking, there are a number of problematic issues that come up when eval is used. Its semantics are confusing and error-prone, and its impact on performance is not always obvious. I’m going to approach it as a tool, and try to clarify and study these issues, in order to help you use the tool effectively.

History and Interface

An interpreter (in the broad sense of the word) for a language is a program that takes text and executes it as code. When you have an interpreter available, exposing it as an eval construct, which does pretty ...

Get Beautiful JavaScript 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.