O'Reilly logo

Beautiful JavaScript by Anton Kovalyov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 much the same ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required