Quoting Wikipedia:
A quine is a computer program which takes no input and produces a copy of its own source code as its only output.@cowboy (Ben Alman) gives the following example for JavaScript:
!function $(){console.log('!'+$+'()')}()Why does the quine work? The above code uses several tricks.
> function foo() { return "abc" } > String(foo) 'function foo() { return "abc" }'
function $() { console.log(String($)) }That is a declaration for a function whose name is $ (a legal identifier in JavaScript). For reasons that will be explained later, we need the above to be a function expression. The following code works:
var prog = function $() { console.log(String($)) };After the assignment, there is a named function expression. Its name $ only exists inside the function and allows it to refer to itself. Calling prog gets us pretty close to a Quine:
> prog() function $() { console.log(String($)) } undefinedAfter calling the function, you first see its output and then its result, undefined.
> !function $() { console.log(String($)) }() function $() { console.log(String($)) } trueThe unary not operator (!) tells JavaScript to parse the function as an expression. Otherwise, we wouldn’t be able to immediately-invoke [1]. true is the result of !undefined.
> !function $() { console.log('!'+$+'()') }() !function $() { console.log('!'+$+'()') }() trueNote that we solved a conundrum: Every character that we add to console.log() becomes part of the program. Which means that we need to log it, too. But if we do so explicitly, the additional characters also become part of the program, need to be logged, etc. Thankfully, referring to the source (via $) allows us to make the repetition implicitly.
(function $(){console.log('('+$+'())')}())As every character before and after the function expression shows up twice in the code, the exclamation mark saves you a total of two characters.