To Survive the Pyramid of Doom…

use the buddy system

After arming us with the basics of JavaScript, @chyldmedford threw us in at the deep end. There are all kinds of scary things here… like callbacks. JavaScript uses asynchronous functions, or callbacks, which allow the program to continue while waiting for data input from a web service or database. Once the data is returned, it is piped into the function that requested it. It helps to think of callback functions as a delivery service. If you order a pizza, would you want to wait at exactly the same place and do absolutely nothing until your pizza is delivered? OR, would you rather just go about your business until the delivery person calls to let you know your pizza is here? The second choice is much more time-efficient, isn’t it?

In the same way, JavaScript functions can be optimized with callbacks to efficiently process external data requests. Consider the code below:

Example of callback function

In order for this function to give us the local high temperature for today, it needs to connect to a weather web service. We could halt the program while wait for the data, but that isn’t really efficient. Instead, we tell the function to return the data, or “call us back,” once it has the requested information.

Callback functions can be extremely powerful; but when nested, they quickly become the bane of a n00b coder’s existence. Nested callbacks create the dreaded Pyramid of Doom, as seen in this snippet of code from a home inventory app that we wrote today in class:

Pyramid of Doom!

Creating programs with callback functions has reinforced the importance of test-driven development (we’re currently using Mocha, Chai, and Travis CI), code quality & debugging tools, such as Grunt and JShint, and paired programming. Without my programming buddy, @LizaHCarter, I’d be stuck nesting parenthesis in callback hell.