A Quick Example of Genetic Evolution in JavaScript: Let’s Make a Baby.

Kieran Maher
Sep 9, 2018 · 5 min read
Image for post
Image for post

“The process of mutation is the only known source of the new materials of genetic variability, and hence of evolution.” — Dobzhansky, 1957.

Genetic Evolution algorithms are truly fascinating to me. The ability to program virtual DNA is just a phenomenal feat of computer science. The ability to write, in code, Darwin’s theory of evolution and to actually see a Survival of the Fittest model in action is just astounding.

I’ve never really touched on genetic algorithms before and decided it was time I started. And what better place to start than the actual, start, right? In this tutorial I will create a ‘stick’, and that stick wants to reach a ‘circle’. Infer from that what you will, but I write family friendly tutorials and it will stay that way.

I am taking incredibly heavy influence from The Coding Train: Coding Challenge #29 as the inspiration for this. Link to it here. He was inspired by Smart Rockets, so while I am not making anything new or original, I hope for it to serve as an example of a genetic evolution algorithm. I am utilising the P5.JS library, that I would summarise as a visual JavaScript library.

Before I can create any kind of genetic algorithm, I first need to set up the actual setting. First I create a very simple HTML page.

I have two libraries for P5. Main handles the drawing to the screen, instantiation of variables, etc. A stick is the line that will be evolving, a population is a collection of sticks, and dna is what I would consider the core of the genetic algorithm. Let’s take a look at the code for Stick:

So a stick has some basic features. It must be able to move, so it has a movement ‘engine’ (for want of a better term) in the velocity, acceleration and position variables. At the moment all movement is controlled by the mysterious DNA function. Before we get to DNA, let’s take a look at population:

Population really isn’t that interesting. It creates 25 sticks, which I believe is sufficient for a population, and then moves them on the screen. Breaking no barriers with this function! DNA:

At this point, DNA does basically nothing. One stick gets one DNA, and one DNA has a set of 200 genes, which is the length of a lifespan for my little stick. Don’t worry, more will be added in due course. The Main file:

So Main is doing a fair few things here. Firstly, we need to create a new generation of sticks, which is an instantiation of population, and then we create our circle, which the sticks will aim for later down the line. Then we are drawing everything to the screen, with the added ability to kill and create a new generation, every time their life cycle ends.

So if we run this as it currently stands, we get this:

Image for post
Image for post
The confused little sticks

Now at this point, it isn’t actually a genetic algorithm, at all. Instead, it is a set of sticks moving at randomly selected vectors, with a dot drawn on the screen. So let’s add the genetic part.

So we want the stick that makes it the furthest, the closest to the circle, to be the stick that passes its genes on to its children. This is basically survival of the fittest: whoever survives the longest, is the one to pass on their genes.

So we can begin to implement this by giving each stick a new variable: fitness.

Fitness will be calculated by the current position of the stick, relative to the position of the circle (target). We can implement this as a function, to calculateFitness on each stick.

Now, we have sticks that have a fitness rating — i.e. they have better genes, because they survived longer. So now we need a way to be able to reproduce those sticks with top tier genes. Enter, the pool:

So, this pool is relatively straight forward in concept. We have already figured above that the most successful genes are the ones that are the closest to the circle. The closer the stick is, then the more times it’s genome will be entered to the pool, and the more likely it is to reproduce. A stick that made it 5% of the way will have a 5% chance to reproduce, whereas a stick that made it 70% of the way, has a 70% chance to reproduce. I hope I explained that well enough. More successful stick = better chance to be reborn as part of a new stick.

The above is two new functions. Selection is, as the name would imply, selecting the parent genes from the gene pool. These genes are then combined to form a new DNA in crossover, which in turn is then assigned to the new stick! That’s pretty much it, since we want to keep this relatively simple and rudimentary.

Pretty cool, our sticks are now able to take the best of the predecessors abilities, and use them to find the circle! If we now look at it in action:

Image for post
Image for post
The still confused but slightly smarter sticks.

After several dozen iterations, it begins to look like they have been dying off, as only a few lines are visible. But that’s not the case: the lighter the stick, means multiple sticks are following the exact same path. This is to be expected, since we have a relatively limited pool of genes.

Image for post
Image for post
The very smart, alpha sticks.

The longer it is left running, the more there will appear only one stick on the screen. This stick represents the optimal stick! The chosen stick. Here they are, the culmination of our genetic algorithm:

Image for post
Image for post
Genius stick(s)!

So that’s a genetic evolution algorithm, written completely in the browser! It’s not a perfect example of genetic evolution, sure, but it is a fine example of it at work. Our little stick can now go on to get the circle and what follows next, is not a topic for today.

As mentioned at the beginning this is heavily influenced by The Coding Train. Link to their repo.

My Full Code.

empowering you with data, knowledge, and expertise

Sign up for DDIntel

By Data Driven Investor

In each issue we share the best stories from the Data-Driven Investor's expert community. Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Kieran Maher

Written by

Data Driven Investor
Kieran Maher

Written by

Software Developer & Analyst. General technology enthusiast.

Data Driven Investor

empowering you with data, knowledge, and expertise

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store