Open In App

Quines in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

A Quine is a program that does not take any input but outputs a copy of its own code. Unlike other languages writing a Quine in JavaScript/NodeJS is quite easy. The approach used is that any function in JavaScript can be converted into a string and can be printed. This allows us to output the code of the function as demonstrated below:

Example:

Javascript




function quine() { console.log(quine.toString()) }


Example: The above function prints its own source code, but it is not a file that can be executed. We will add a statement so that it could be called.

Javascript




<script>
  function quine() {console.log(quine.toString() + " quine();")} quine();
</script>;


Output:

"function quine() { window.runnerWindow.proxyConsole.log
(quine.toString()+\" quine();\") } quine();"

Note: We needed to add something extra in the log statement to achieve our goal. The `;` at the end is unneeded.

We can make it more elegant. We know that JavaScript can make a function run as soon as it is defined by using an IIFE (Immediately Invoked Function Expression). We will incorporate this in our code as shown below:

Example:

Javascript




<script>
  ( function quine() {console.log("( " + quine.toString() + " )()")} )()
</script>;


Output:

"( function quine() { window.runnerWindow.proxyConsole.log
(\"( \" + quine.toString() + \" )()\") } )()"

Note that the console.log() statement is manipulated as required. We can further make it more beautiful by adding the Arrow-Operator and Format-Strings into this equation. This produces the code as given below.

Example:

Javascript




($=_=>`($=${$})()`)()


To understand the code we remove the IIFE and extra parentheses in the format-string. The spacing is added to make it further clear. The first `$` is a variable that contains an arrow function. `_` is a random parameter for the arrow function that remains unused. After the arrow, this is our format-string which can be divided into 2 parts, the String, “$=”, and the Variable which is first `$` itself. 

Example:

Javascript




$    =    _    =>    `$=${$}`


A Quine needs to be executable but it does not mean that a program that results in errors cannot be a Quine. The below example is still an example of a Quine. This program when executed as a .js file with the help of NodeJS outputs its own source code. NodeJS returns an error at the first line and the rest of the code is how the error looks like.

Example:

Javascript




throw 0
^
0




Last Updated : 11 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads