I was thinking “programming is easy, but good programming is hard.” As a way of demonstrating programming is easy, I remembered the second program I learned to write after “Hello World.”
1 2 |
10 PRINT "HELLO WORLD." 20 GOTO 10 |
I asked myself how I would implement that simple infinite loop in JavaScript, then realized there are a bunch of ways to create an infinite loop.
The Conditionless For
1 2 3 4 |
for(;;) { console.log('Hello World.'); } |
The Unchanging Condition:
1 2 3 4 |
while(1<2) { console.log("Hello World."); } |
Infinite Recursion:
1 2 3 4 5 |
function helloWorld() { console.log('Hello World.'); helloWorld(); } |
The For Loop Reset:
1 2 3 4 5 |
for(var i = 0; i<2; i++) { console.log("Hello World."); i = 0; } |
60 Hello Worlds Per Second (or slower infinite recursion):
1 2 3 4 5 |
function helloWorld() { console.log("Hello World"); var repeat = window.requestAnimationFrame(helloWorld); } |
Note: This would also work with setTimeout()
or setInterval()
.
Global Condition, Local Change (a variant on The Unchanging Condition)
1 2 3 4 5 6 7 8 9 |
var iterator = 0; while (iterator < 5){ console.log("Hello World"); increment(); } function increment(){ var iterator; // creates local var iterator++; } |
That’s all I can come up with off the top of my head. If you can think of one I missed, please add it in the comments (without <script></script> tags, please)
Update (2/21/18)
Complementary Recursion:
1 2 3 4 5 6 7 8 9 10 |
function helloWorld() { console.log('Hello World.'); helloUniverse(); } function helloUniverse() { console.log('Hello Universe.'); helloWorld(); } |
The Self-Invoking Recursive Hello:
1 2 3 4 |
(function hello() { console.log("Hello World"); hello(); }()); |
Callback Hello (a variation on Complementary Recursion):
1 2 3 4 5 6 7 |
function hello() { console.log("hello world"); comeback(hello); } function comeback(dacaller) { dacaller(); } |