Skip to content

Instantly share code, notes, and snippets.


JohnReeves/ Secret

Last active Oct 11, 2017
What would you like to do?

1. Last Worksheet


Find and open your JSFiddle link from last week - as we're going to add random mutations to our emojis!

2. Global Variables

Mutations are an incredibly small chance of something "different" from the parents genetics happen - this is how evolution slowly works.

Firstly, we need to create ourselves a random variable to hold the chance of something random happening. Global variables go at the top of the page. I'm going to give my emojis a 2% chance of mutating like this:

var mutationChance = 2;

My code looks like this:


3. Genetic Algorithm

We can then go back into our breedEmojis function and take a look at the chance of each attribute being taken from the parentA or parentB.

Because we're calculating chance as a percentage (1 to 100) - we can add an if to check if the percentage is less than our mutationChance like this:

if(fillChance < mutationChance){
} else if (fillChance < 50){
  babyEmoji.fill = A_fill;
} else {
  babyEmoji.fill = B_fill;

We can then mutate that attribute by calculating an entirely random value, which is how we set up our original emojis:

babyEmoji.fill =  fillColours[randomNumber(0, fillColours.length)];

You'll need to do this for all your properties that you want to mutate. You can also have a go at increasing the mutation rate by increasing the mutationChance variable.

My code looks like this: Imgur

4. Finishing

This is the final worksheet - but you can always extend your project by adding more attributes to your emojis, different features they could all have!

Don't forget to save your JSFiddle and send us your awesome project! 🌟

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment