Blog · 5 min read ·

How I built a JavaScript REPL from scratch

A REPL (read-eval-print loop) is the simplest kind of programming environment: you type a line, it runs, you see the result, repeat. Browsers already have one in DevTools, so why build another? Because building it is the fastest way to understand what eval, scopes and iframes actually do. You can try the finished REPL here.

1. Don't run user code on your own page

The first rule: code typed into the REPL must not be able to touch the page around it. If it ran with the page's privileges, one line could read cookies or rewrite the DOM. So every line runs inside a hidden <iframe sandbox="allow-scripts">. Without allow-same-origin, the iframe gets an opaque origin: it can run JavaScript, but it can't read the parent page, its storage or its cookies.

The page and the iframe talk with postMessage. The page sends { code }; the iframe sends back results, console output and errors.

2. Make variables stick between lines

Calling eval indirectly, as (0, eval)(code) or through an alias, evaluates code in the global scope, so var x = 1 on one line is still there on the next. But let and const at the top level of an indirect eval live in a scope that disappears when the eval ends. The fix is a small rewrite before running: top-level let and const become var. It isn't perfect (you can redeclare a "const"), but it's exactly what you want in a scratchpad.

3. Top-level await

Regular eval doesn't allow await outside an async function. When a line contains await, the REPL wraps it: first as an expression, (async () => (code))(), so the value comes back; if that fails to parse, as a block, (async () => { code })(). The returned promise is awaited and its value printed.

4. Printing values like a real console

String(value) is useless for objects, and JSON.stringify fails on Maps, Sets, functions and circular references. So the REPL has its own small formatter: it quotes strings, shows arrays and objects with a depth limit, prints Map(2) { a => 1 }, names functions and classes, and replaces repeated references with [Circular]. console.log inside the sandbox is replaced with a version that formats its arguments the same way and posts them to the page.

5. Surviving infinite loops

Type while (true) {} and the iframe's thread is stuck forever. The page can't interrupt it, but it can stop waiting. Every run starts a three-second watchdog. If the sandbox hasn't answered by then, the page deletes the iframe and creates a fresh one. You lose your variables, but the page keeps working.

What I learned

  • Direct and indirect eval are different features hiding behind one name.
  • An iframe with sandbox="allow-scripts" is the cheapest real isolation the web gives you.
  • Most of a "console" is the formatter, not the evaluator.

The whole thing is a single small JavaScript file with no dependencies. Open the REPL and try to break it.