Oops!: I Fixed a Bug in My Random Quote Generator

Turns out, my Quote Generator wasn’t quite complete. I tweeted it out for all the world to see, and @FreeCodeCamp caught something I missed.

When I was first coding this project, I was trying to use a for loop to cycle through all of the quotes. I took it out once I realized that I didn’t want to cycle through since I’m using randomized values. So, for a second, I thought I screwed something up and the code reverted back to that point.

I clicked the button a handful of times and it seemed to be working as expected. But clearly there was a problem somewhere, so I kept clicking. Lo and behold, my quote div completely disappeared!

In my last post, I mentioned how Bonfires are helping me get better at approaching solving these problems. I’m also getting better at debugging. I instantly opened the console to look and see what happened when I clicked my generator button. I printed to the console log to show me when it generated a number and when it displayed successfully. It took about 15 tries before my code broke and I got that cute little error box that told me what was wrong.

This is my code before:

var x = Math.floor((Math.random() * quotes.length) + 1);

And this is my code after:

var x = Math.floor((Math.random() * quotes.length - 1) + 1);

Can you spot the difference?

Turns out, I wasn’t giving my code a proper range to pull the number from. Although quotes.length might equal 13, that also means that I need the random number to stop at index 12. My code was including 13, which doesn’t exist, and broke my generator.

Thanks again to Free Code Camp for finding that error for me. It’s always a little disheartening when you are proud of a project then someone finds a flaw that you missed. But, I’m learning it’s actually pretty difficult to accurately test your own code. My goal was to make my code work, so I tested it to make sure it worked and it did. But when FCC tested it, they tested it to see if it would break; something I didn’t even think about.  After realizing that, I ran my generator over and over again until I was sure there would be no more errors (over 300 times!).

Here’s my now fully functioning Random Quote Generator.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s