m15o.net projects journal about

A quine is a program that outputs its own source code.

When a program runs, its state can changed. When that program is self-replicating, the changes in its state are persisted when it outputs itself. The code acts as an image that carries its own execution environment and its data.

A simple quine

Let's look at a simple example:

<body>
<script>
const src = document.currentScript.textContent,
q = '<textarea></textarea><button onclick="save()">save</button>',
save = () => console.log(`<body>\n<script>${src}<\/script>`)
document.body.innerHTML = q
</script>

When you press save, the console prints the source code. However, if you type something in the textarea and press save, the source code won't contain the changes. It's not a quine, and a useless one: whatever you typed is gone. Let's improve it:

<body>
<textarea></textarea>
<script>
const src = document.currentScript.textContent,
save = () => console.log(`<body>\n<textarea>${document.querySelector('textarea').value}</textarea>\n<script>${src}<\/script>`)
document.body.insertAdjacentHTML('beforeend', '<button onclick="save()">save</button>')
</script>

What makes quines useful

A quine makes it possible to have self-contained programs, often within a single file. These files can be stored as snapshots, shared or forked.

By contrast, a simple save file requires the program to be installed, and the version to be compatible in order to open. Since quines carry their own run instructions, just a single file is needed.

refs: html-quine, wombat