Shitty First Code

I got my degree in English Literature, and there have been a few brief periods in my adult life when I made attempts at “being a writer” (a phrase that’s as nebulous to me as “when I grow up”). To that end, I’ve read a couple of books by a couple of writers that have more or less stuck with me. The first, which I recommend to anyone who writes in any capacity, is Stephen King’s On Writing. The second, Bird By Bird by Anne Lamott, contains a particular chapter that I may never forget. It’s called “Shitty First Drafts.” (You can read the excerpt in PDF format online here, if you’re so inclined – it’s about a 5ish minute read, and it’s rather funny.)

I revisited Ms. Lamott’s advice on writing such first drafts tonight after I had worked through some coding problems on a new website I just discovered called Codewars – if you’re interested, you can sign up here. It’s fun, it’s free, and I’m finding it to be a great way to flex my mental muscles! I made it through the first several problems before getting stuck on one (which is why I’m taking a break to write this post now).

One of the truly great features about this website is that, after you submit your answer, it shows you some of the more optimal and clever submissions by other users – in most cases using obscure code or tricks I’d never even thought possible. It’s a great way to learn, certainly, but for someone as competitive as I am, it’s also daunting in a way. Part of me always wants to be the best at what I’m doing, to excel, and so it’s easy for my inner critic to convince me that, even though I came up with an answer, it just wasn’t good enough. Why hadn’t I thought of that? I’m a smart guy, is the most basic solution all I’m really good for?

In my particular case, I’m solving the problems using JavaScript (though, if time permits, I’d like to revisit them using at least one other language). I’ve been casually familiar with JavaScript for years, but I am not yet an expert and have still only barely scratched the surface of what is possible with this language. I should really be proud that I’m coming up with solutions, period. And so I started thinking about that when I stepped away from my apartment to take the dogs out. I need to be okay with shitty first code.

According to Lamott, “[a]lmost all good writing begins with terrible first efforts.” I believe this is true, and I believe that it extends beyond writing fiction/nonfiction to writing computer code, as well. I think if I intend to get anywhere with a career in development, I need to start by accepting that my first efforts are going to be imperfect and suboptimal. Accepting shitty code doesn’t mean settling for being a shitty coder; it means understanding that my first attempts will likely be laughable to a more seasoned developer, but also knowing that I will eventually hone my skills and improve my knowledge of what can be done within the constraints of the language. The most important thing at this point is actually doing it without giving up, so that I can come to an understanding of the fundamental algorithm for the problem I’m trying to solve. As I progress, I’ll take note of what others have done, and I’ll admire and appreciate their ingenuity, but I’ll also do my best not to let the superiority of their methods intimidate me. I’ll see their more optimal code as an opportunity to learn. Instead of beating myself up, I will slowly start to build myself up instead.

So here’s to shitty code.

My first script: an update (now with jQuery)

I haven’t posted in a few days, but I’ve still been steadily reading and researching to up my web development knowledge. I took a brief detour from JavaScript to work through some of the Python exercises on Learn Python The Hard Way (which, so far, I highly recommend), I’ve read through most of the jQuery Core documentation, and wrote another basic script to use with Greasemonkey in Firefox (I may write about that separately in a future post).

However, while viewing newbie-friendly open source projects on Up For Grabs, I came across one which mentioned issues in something called Codacy. I had never heard of this, so I signed up for an account and ran it on my Github repo for the prime number script I wrote recently. It gave me a B, mentioning several issues with my usage of console.log statements. In that original project, I created a bare bones web page, but all of my output went to the JavaScript console, which is more intended for development purposes. I did not have any visible output if the console was closed. To get rid of these errors, I decided to rework the code a bit.

I started by adding the index.html file to my repo, then added an empty unordered list which I planned to add list item elements to with the results of each prime number I checked in my script. I attempted to stick with vanilla JavaScript, but after a couple hours of futile attempts, I finally resorted to using jQuery. (If you’re interested, the repo is located here.)

When I converted my newly updated JavaScript code to jQuery, I noticed that my code became much more concise (which I appreciated). Here’s my code as it stands currently (and holy hell, was it hard to get this formatted right in WordPress’s editor):


$( document ).ready(function() {

	//find and store <li> DOM element with ID "output" to list
	var list = $( "#output" );

	function isPrime(number) {
		var remainder;

		//this will store each new <li> element as "item"
		var item;

		//this will store string to be appended to new list item
		var result;

		//prime numbers must be greater than 1
		if (number <= 1) { 			//create new <li> DOM element
			item = $( "<li/>" );
			result = number + " is not greater than 1! False.";
			item.html( result ).appendTo( list );
			return false;
		}
		else {
			for (var i = 2; i < number; i++) { 				remainder = number % i; 				if (!remainder) { 					item = $( "<li/>" );
					result = number + " is not a prime number! False.";
					item.html( result ).appendTo( list );
					return false;
				}
			}
			item = $( "<li/>" );
			result = number + " is a prime number! True.";
			item.html( result ).appendTo( list );
			return true;
		}
	}

	isPrime(0); //should return false
	isPrime(1); //should return false
	isPrime(2); //should return true
	isPrime(17); //should return true
	isPrime(7919); //should return true
	isPrime(23456789); //should return true
	isPrime(10000000000000); //should return false
});

From the start, this code is different because it’s wrapped in jQuery’s built-in functionality to check that the document has loaded, so I don’t go messing with the DOM before it’s ready for me to. To target the unordered list element on my index page, I find it with jQuery (targeting its ID, “output”) and save it to a variable named list.

The next addition to this script is a variable named “item,” which I’ve designated to store the new list item elements I’ll be adding to the output list. I’ve also created a variable named “result” to which I’ll save the strings describing the results of running the function.

Inside the conditional statement that checks whether the number is less than or equal to 1, I’ve replaced the invisible console.log statement with the new code that creates and appends a visible list item to the page. I did this by creating and saving a new list item element to item with jQuery. I then save a string stating that the inputted number is not greater than 1 and is thus false. Finally, to get this list item element onto the page, I again use jQuery to add the result string within the li tags and, using handy jQuery chaining, append it to the list I targeted earlier in the script. I then return false in case I wish to use the return value for something in the future (though I can’t currently imagine how I’d use it).

I didn’t have an else statement in my original script, since the number would either be return false and exit the function or otherwise continue on to execute the lines of code which followed, but I put an else statement in the revised script. It might be overkill, but I added it for the sake of thoroughness. Inside the for loop which checks for factors (returning false if they’re found, since a factor would signify the number isn’t prime), I used the exact same method described above to create a new list item element, fill it in with a string, and append it to the targeted list before returning false.

Should the for loop finish without returning false, I know that I’ve found a prime number – so I immediately use the same method I devised to add a list element stating that the number being tested is a prime, returning true. For fun, I added a fun new number I knew to be prime (23, 456, 789) to further test my program functionality. It worked!

It took me hours to get this seemingly simple program debugged and running properly, but I feel like I’ve learned a good deal in the process. I’ve been doing my absolute best to commit my changes regularly with git after making a change to the code so that it’s easy to briefly describe what I’ve done. Using git properly is probably one of the most difficult skills I’ve had to learn, but it’s essential…and I’m only scratching the surface yet. I experimented with branching for the first time, though I still don’t quite think I’ve got the hang of it. I find that I’m becoming more and more mindful of the need to commit the more I code. And I incorporated jQuery for the first time! I’m hungry to put it to further use. While I do want to master the basics of JavaScript without relying too heavily on a library, the platform cross-compatibility of jQuery makes it hard not to use. I’m sure it’ll pop up in quite a few of my scripts going forward.

Now I need to go to bed. Thanks for reading!

Photo of a worn house with random colored numbers hand-painted on the side

My first JavaScript program!

Well, that’s not entirely accurate. I’ve written scripts before, but they’ve all been fairly specific in their scope (hiding DOM elements on a particular page for my convenience, for example), and it’s been years. So I’m basically starting over.

In today’s exploration, I came across this list of questions a front-end developer might reasonably be expected to answer in an interview, so I decided to start working through them. The first problem is to develop a function which checks whether an inputted number is prime. All things considered, it’s a pretty basic problem, but it’s been a long time since I even thought about prime numbers, so it took some minor mental gymnastics to get to the solution. Here’s my code:

function isPrime(number) {
	var remainder;
	if (number <= 1) {
		console.log("Number must be greater than 1!");
		return false;
	}
	for (var i = 2; i < number; i++) {
		remainder = number%i;
		//console.log("Dividing " + number + " by " + i)
		if (!remainder) {
			//console.log(i + " is a factor! " + number + " is not prime. Exiting!");
			return false;
		}
		/*else {
			console.log("The remainder of " + number + " divided by " + i + " is " + remainder);
		}*/
	}
	//console.log("Looks like " + number + " is prime! Congrats!");
	return true;
}

console.log(isPrime(0)); //should return false
console.log(isPrime(1)); //should return false
console.log(isPrime(17)); //should return true
console.log(isPrime(10000000000000)); //should return false

As you can see, it’s primitive and anything but optimal. I doubt a prospective employer would be impressed by my ingenuity, but it’s a starting point nonetheless.

Before beginning, I had to understand pretty well what a prime number was. I now understand that it is any number, greater than 1 (a stipulation I initially overlooked), which is not divisible by any number other 1 or itself. Before jumping into coding, I wrote out some pseudocode in an attempt to guide my thinking. It went something like this:

  • Accept number as input parameter
  • Loop iterator from 1 through (number-1)
    • If remainder of number divided by iterator is 0, return false
  • Else, return true

To put this into action, I declare function isPrime with a single parameter, number. I then declare a variable, remainder, which I’ll use shortly. The next line checks whether number is less than or equal to 1, logging a warning to the console and returning false if this condition is true. If the number passes this test, I then proceed into a for loop. It is here that I realized I’d made an error in my pseudocode; rather than starting with 1, I needed to start with 2! So I set a for loop to run with iterator, i, from i=2 until i<number, incrementing by 1 at the end of each pass.

At the beginning of each pass, I divide number (the input) by i using the modulo operator, storing the modulus as the remainder (though I learned while typing up this blog post, that modulus and remainder areĀ not the same thing…for the purposes of this example, I’ll go ahead and use them interchangeably). If remainder is zero, that means that we’ve found ourselves a factor which divides evenly into number, so number is not prime – thus the function returns false. If remainder is not zero, the loop continues, checking the remainder with each pass until the condition is met. If, during the execution of the loop, false is not returned, then the number must be prime, thus true is returned.

I called the function against four test cases mentioned in the website – 0, 1, 17, andĀ 10000000000000 – expecting the function to return false, false, true, and false, respectively. And my program passed the test each time! It’s a minor victory, but I’m proud to have solved the problem without cheating or asking for external help (save for some cursory research into the concept of prime numbers to make sure I had a clear understanding).

If I were to improve this program, I would probably remove the console.log statements I put in initially to debug. I would also like to figure out how to write the results to the barebones HTML document I included the script in to run it. As it stands right now, the results are posted only to the JavaScript console in my browser, but not to the page itself. I intend to figure out how to make this happen soon. As for now, it’s onto the next problem.

I’m opening it up now, I’m peeling off the bark

Hi, I’m Jared Caraway. On the advice of a new acquaintance who makes a living off of web development, a long-term goal I’m aiming to replicate in my own work life, I am starting a blog to document my progress and the things I’m learning. I’m terrible at picking clever names for things (which is why I named my band Jared and The Jewelers), and I’m a music lover, so I decided to go with something musical. Pinegrove is one of my favorite bands, so I went with one of their songs (though it’s admittedly not one I consider a favorite or am even particularly familiar with). I thought the title was apt. A failure to see the forest for the trees is usually a negative trait signifying one’s failure to zoom out from the granular level to get the bigger picture; however, in my case, I’m attempting to get as granular as possible in my journey. I want to see the trees in the forest that is the World Wide Web; more than that, I want to peel off the bark to see exactly what makes up the trees.

Since this is my first post, perhaps it’s appropriate to describe my background a bit. At the time I’m writing this, I’m 30 years old. I’ve been using computers almost my whole life, going back to a Commodore 64 hooked up to a shitty television at my grandma’s house, and I’ve been an avid user of the Internet since somewhere in the mid-90s when it became affordable to adopt the technology needed to connect (I started exploring with a 14.4 kbps modem, dinosaur-like equipment by today’s standards). It didn’t take me long to become curious about the technology driving the (very primitive) websites I was using. I experimented with creating my own web pages using free hosts such as Geocities and Angelfire, quickly moving past the extremely limiting built-in builder tools to the HTML code underneath. I remember leaning heavily on sites such as HTMLGoodies.com for advice, and it wasn’t long before I started cursorily digesting the then-new concepts behind Cascading Style Sheets, and then the most basic level of JavaScript functionality and syntax.

The ability to control a computing machine has always fascinated and appealed to me. I didn’t delve deep in my early explorations because I get distracted pretty easily (and I was pretty young, so my schoolwork took precedence). But my desire to learn how to code never faded; I went to a science and engineering high school with the intention of becoming a software developer so I could create my own video games. From there I learned low-level BASIC programming which I used to make rudimentary TI calculator games, and in school I learned the basics of C++ and Java (the latter of which I didn’t quite get the hang of, and which pushed me away from development). I gave up on my dreams of making video games by the time I graduated high school, changed majors back to Computer Science briefly in college before quickly getting discouraged at the amount of time I was sinking into what felt like futile attempts at grasping many abstract concepts, and ended up getting my degree in English Literature just so I could get the hell out of school and get a “real job.”

Somewhere in the early 2010s, I stumbled across WordPress, which reignited my interest in web development and design. I began freelancing on a number of sites as a subcontractor for a few companies, one local and one based on the east coast, but my interest ultimately fizzled as I found full-time employment in the legal field, where I’ve been for just over half a decade. I’m a fast learner and adaptable, so I quickly gained a foothold in the industry, working my way up to paralegal.

Then I met a woman, fell in love, and moved from my lifelong home in the DFW metroplex to her childhood hometown just outside of Houston to raise our first kid together. This move involved me leaving my job and taking a leap of faith (with some savings and a lot of help from her parents, who are right around the corner from us), quitting my job without one to land at once we arrived. I delivered pizza several years back as a side hustle, so I was counting on getting hired at the franchise location a few minutes away from our apartment until I found something stable and long-term. But that fell through, and I found myself hungrily searching for a job as my savings dwindled.

While scanning through a list of recent postings in my area, I saw one for an Angular.js developer. I’d heard of Angular, but never examined it at all. I was interested to see what skills would be required of a developer of this shade and, honestly, what the pay range was. I was stunned at the list of required skills, but the pay was also tempting. Starting out, I could easily make double what I was pulling in doing work that didn’t particular interest or inspire me. I felt like the realm of web development deserved a second (or third, or fourth, or whatever) glance.

I was never truly a professional web developer, but I was at least in the loop for a year or two. Technology moves fast; in my absence, a lot changed (for the better), but it got a lot more complicated, too. There’s a lot for me to learn if I want to hit my goal of being a full-stack developer, and it’s going to be a long and (I have no doubt) frustrating road. But I also hope to find some joy and fulfillment in the technical and creative aspects of the trade. Of course, it’s just as likely that I’ll get discouraged at some point in the process of working a full-time job (which I as yet am not prepared to get hired for in a web-related capacity) and balancing my duties as a good boyfriend (and husband, when it makes financial sense) and, perhaps more importantly, a father.

I’ve been trying to learn a little bit each day, and I’m admittedly taking something of a scattershot approach. There’s so much to learn, and I’m not sure where best to start. I’ve done some lessons in Codecademy, gleaned a few tutorials, and, most recently, paid a visit to my local library to check out a small stack of books I hope to gain some insight from. The real challenge is that I know it won’t pay to learn a little bit about each language, but to pick one to really master. After all, it is my understanding that the underlying concepts in web/software development, the algorithms and design patterns, are most important, independent of the particular language being used.

And that’s kind of where I’m at on my journey. I’m leaning toward mastering JavaScript, though I am also interested in learning Python and Ruby. I may still tinker with the latter two to see if they catch my interest, but it still remains for me to pick something to focus on and just dive in. Regardless of the language I land on, I’m still going to need to be proficient with HTML, CSS, and JavaScript at the end of the day, so I picked up books on each topic. I also checked out a book about SQL and one about AJAX, since I figure both technologies will be beneficial to have an understanding of going forward.

The way forward is not clear to me. There are many paths I can take. It is overwhelming to sift through the mountains of information available to me, but it’s a task I’m going to do my best to accomplish if I have any real hope of one day calling myself a web developer with full confidence.

Let’s see what happens.