DEV Community

Cover image for Quine(s) in JavaScript
Parth Agarwal
Parth Agarwal

Posted on • Updated on • Originally published at

Quine(s) in JavaScript

Quine is a program that takes no input but outputs a copy of its own code. Unlike other languages writing a quine in JavaScript/NodeJS is quite easy.

Here we go!

function quine() { console.log(quine.toString()) }
Enter fullscreen mode Exit fullscreen mode

The key here is that any function in JavaScript can be converted into a string and can be printed. Also, console.log is not the only option, alert can be used too. Although it will not work in a node terminal.

Above is a function that prints its source code but it is not a file that can be executed. So let's add a Call statement,

function quine() { console.log(quine.toString()+" quine();") } quine();
Enter fullscreen mode Exit fullscreen mode

Note that we needed to add something extra in the log statement to achieve our goal. And ; was probably not needed.

Let's make it a little elegant, We know that JavaScript can make a function run as soon as it is defined, By using an IIFE (Immediately Invoked Function Expression).

( function quine() { console.log("( " + quine.toString() + " )()") } )()
Enter fullscreen mode Exit fullscreen mode

Note that we manipulated the log statement as required.

For some more Quines in NodeJS:

Now let's take Arrow-Operator and Format-Strings into this equation and It becomes almost eye-blindingly beautiful!

Enter fullscreen mode Exit fullscreen mode

To Understand let's remove IIFE and extra parentheses in the format-string. And also, add some spacing.

$    =    _    =>    `$=${$}`
Enter fullscreen mode Exit fullscreen mode

So, the first $ is a variable that contains an arrow function.
_ is a random parameter for the arrow function which 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.

Lastly, A Quine needs to be executable but it doesn't mean that programs resulting in errors can't be a Quine. Here is an example

throw 0
Enter fullscreen mode Exit fullscreen mode


This program when executed as a .js file with the help of NodeJS outputs its own source code.

How this works is, NodeJS returns an error at the first line, the rest of the code is how the error looks like.

If you make your own JS Quine or you want to share Quine in other programming languages, then please do write in the comment section.

Top comments (2)

siddharthshyniben profile image

Technically this is not a quine because it is reading it's own source code

codekhal profile image
Khushal Vyas