Self-replicating code

Fun fact: you can write code that replicates itself without reading itself! This is known as a quine, and you can make one in any Turing-complete language.

This turns out to actually have applications! Implicit self-reference is how we get Gödel's incompleteness results.

Here's some JavaScipt code that does just that. It's not well written and I decided to try to write it without referencing other online materials. The Wikipedia page linked earlier has much more compact examples, and even has quines between multiple programming languages (like Java code that returns C++ code that returns the original Java code).

function copy(str) {
    var output = str + "\n";
    var repl = "function replicate() {\n\tdocument.getElementById(\"replicate\").innerHTML = out;\n}\n";
    output += "var out = copy(\"" + str.replaceAll("\\", "\\\\").replaceAll("\n", "\\n").replaceAll("\t", "\\t").replaceAll("\"", "\\\"") + "\");\n";
    output += repl;
    return output;
}
var out = copy("function copy(str) {\n\tvar output = str + \"\\n\";\n\tvar repl = \"function replicate() {\\n\\tdocument.getElementById(\\\"replicate\\\").innerHTML = out;\\n}\\n\";\n\toutput += \"var out = copy(\\\"\" + str.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"\\n\", \"\\\\n\").replaceAll(\"\\t\", \"\\\\t\").replaceAll(\"\\\"\", \"\\\\\\\"\") + \"\\\");\\n\";\n\toutput += repl;\n\treturn output;\n}");
function replicate() {
    document.getElementById("replicate").innerHTML = out;
}

Output:



        

return to home page

Accessibility