Project Nayuki


Brainfuck interpreter (JavaScript)

Program

Description

This is an interpreter for the brainfuck programming language, written in JavaScript. It allows you to see the internal state of the brainfuck virtual machine.

Some important behaviors of this interpreter implementation:

  • In the input program code, any character outside of the 8 brainfuck commands (<>+-[].,) are ignored. Effectively, most characters are code comments.

  • During execution, the memory is unbounded for positive addresses.

  • Attempting to decrement the memory address below 0 will raise an exception and halt the execution with no chance for recovery.

  • Each memory cell is an unsigned 8-bit integer. The values wrap around upon overflow/underflow.

  • The input is captured when the program is loaded, and cannot be changed afterward.

  • Reading past the end of the input yields 0. This is indistinguishable from reading the byte value 0.

  • The interpreter is not optimized for speed; it’s optimized for a readable codebase. A fast web-based interpreter should use WebAssembly, and a fast desktop interpreter should use C/C++/Rust/assembly.

The source TypeScript code and compiled JavaScript code are available for viewing.

Examples

Title & demo Code
Hello world
++++++++++[>+++++++>++++++++++>+++>++++<
<<<-]>++.>+.+++++++..+++.>>++++.<++.<+++
+++++.--------.+++.------.--------.>+.
Echo the input
,[.,]
Reverse the input
>,[>,]<[.<]
Infinite loop
+[]
Binary counter (explanation)
- [ >[->]+ +[-<+]- ]
Mandelbrot set mandelbrot.b by Erik Bosman
(takes 10 521 107 970 steps)

More info