A Random Walk In JavaScript

I've been exploring the concept of "emerging complexity" over the last few weeks and it has opened my eyes to a number of interesting concepts, one of them being randomness. What even is "randomness"? What does it mean to say that a process is "random"? Merriam Webster defines it as such:

lacking a definite plan, purpose, or pattern

Taking the face value of that definition, "randomness" doesn't sound very useful at all. As it turns out, nature finds clever ways to use randomness all the time. It has been said that the level of diversity found in nature can be attributed to random mutations following natural selection. Basically nature rolls the dice to determine whether you're going to get the exact gene mashup that your parents so graciously donated, or a slightly tweaked version with some amount of randomness.  I thought I'd take a moment to appreciate randomness with a little visualization of a random walk in JavaScript.

Taking a Random Walk

JavaScript gets its random fix from Math.random() which returns a pseudo-random number between 0 and 1. I modified this to return a random number between two arbitrary values, and setup a canvas that selects random x and y values and draws a line to that point. The function that draws the line is a recursive function that makes use of requestAnimationFrame to try and keep the animation running at 60FPS. Here's the result:

It's just a squiggly line that moves, well, randomly - but it's pretty mesmerizing to watch. Even though this isn't an "intelligent" piece of code, once it starts there's no human intervention determining where it goes - I find that fascinating. Randomness pops out in all kinds of interesting places in programming. Neural networks use randomness to seed initial values in matrices. Generative art incorporates techniques like the one used in this visualization to create some amazing visuals. Randomness is also one of the foundations of cryptography. I believe getting comfortable with randomness is a key step in breaking down the meaning of "complexity", and I'll be diving more into randomness and its role in complexity in future posts. For now, hit refresh a few times and enjoy a small, not-so-complex piece of "art" brought to you by a little line taking a random walk in JavaScript.

View The Visualization Code Here

Show Comments