Commissioned for this museum · after Kleene's recursion theorem, and the form named for W. V. Quine
A Program That Writes Itself
JavaScript·1960·2 lines·127 bytes
const s = "const s = %s;\nconsole.log(s.replace(\"%s\", JSON.stringify(s)));";
console.log(s.replace("%s", JSON.stringify(s)));Curator’s note
A quine is a program that prints its own source and reads no input — no opening its own file, no cheating. This one is 128 bytes and its output is byte-identical to the file you are looking at.
The trick every quine performs is the same. A program cannot contain a literal copy of itself, because that copy would have to contain a copy, and so on forever. So it stores its own text *once*, with a hole punched in it where the text should go, and fills the hole with a quoted copy of itself at run time. Here the hole is %s, and JSON.stringify does the quoting — it is the piece that turns code into data by adding the quotes and escaping the backslashes.
Watch the second line do double duty. s.replace("%s", …) finds the hole in the *data*, but that same "%s" is sitting there in the *code* as an ordinary string literal. The two occurrences are the same characters playing different parts, which is why the file reads as though it says everything twice while containing nothing twice.
The escaping is where quines are actually won or lost. \n in the stored string is two characters, and must survive as two characters; the escaped \" around the inner %s must come back escaped. Get one of them wrong and you get something that looks like a quine and is off by a byte, which is the same as being off by everything.
Every language that can quote a string can do this. Kleene's recursion theorem says so, which makes the quine one of the few pieces of code in this building that is a proof of something.