liveBook · Manning

Code compilation

As explained in Secrets of the JavaScript Ninja, Second Edition

The process of translating a program or expression into an internal form suitable for execution.

A regular expression is compiled when it is created: the JavaScript engine parses it and converts it to an internal representation. Matching is a separate execution phase. section 10.3

Avoid needless compilation when a pattern is reused:

  • Create a regex once and store it for later use. Browsers may cache identical patterns, but don’t rely on that, especially for complex expressions. section 10.3
  • Use a literal for a fixed pattern or a RegExp constructor when the pattern must be built from a runtime string. section 10.3
Listing 10.2. Two ways to create a compiled regular expression
  const re1 = /test/i;                                      #A
  const re2 = new RegExp("test", "i");                      #B
  assert(re1.toString()=== "/test/i",
         "Verify the contents of the expression.");
  assert(re1.test("TesT"), "Yes, it's case-insensitive.");
  assert(re2.test("TesT"), "This one is too.");
  assert(re1.toString()=== re2.toString(),
        "The regular expressions are equal.");
  assert(re1 !== re2, "But they are different objects.");

Compare literal and constructor forms; both create compiled regexes, but each creates a distinct object. section 10.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains parsing and conversion into an internal representation, but leaves that representation unspecified.
Examples
Compares literal and constructor creation, including case-insensitive matching and distinct object identity.
What it assumes
Assumes familiarity with regular-expression literals and constructors rather than teaching their syntax from zero.
What you can do after
Apply precompilation with JavaScript regex literals or RegExp constructors to reuse patterns.
How it connects
Connects regular-expression compilation with pattern execution and JavaScript regular expressions.

Also explained in

Compare how 7 books explain code compilation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.