Delicious thoughts run through my mind when the phrase from scratch precedes anything that may possibly end up in my stomach. It immediately conjures up memories from my childhood days spent at my grandparent’s house. Visiting was always a little boring at first. They didn’t have the newest Nintendo game cartridges, they lived on Northern Minnesota’s Iron Range and enjoyed bringing me to rummage sales. As bad as that sounds to any child below the age of being-able-to-ride-a-go-cart-by-yourself, it would always end up better than it started when my grandma would bake homemade pie with garden-picked rhubarb. Within minutes of being put into the oven, the bitter and rustic, sweet smell would fill the house and tease our senses.

So what does this have to do with making rad JavaScript? Well, there are lessons to be learned from how things have been done in the past. Although the prep time of my grandmother’s pie is a bit prolonged – in comparison to visiting the closest Jubilee food market – it offers a specificity to our tastes that no pre-made and mass-produced Pillsbury pie can match.

JavaScript is like pie, but don’t go trying math equations about the circumference of a circle, like Math.PI, and expect gooey pie filling to come gushing out of your USB ports. Rather, it is so much more of a delight when it’s homemade…from scratch. It will take longer at first, but after a short time productivity and understanding will skyrocket. So now that we are on the same page, let’s explore some things to which many developers are oblivious.

Dash of Data-Structures

This topic is one that may be scary to many people and frankly they should be scared. Data-structures are at the core of computational science and are not an easy topic, especially to those from an amateur background like mine. It wasn’t until I started my university computer science classes that I even started to contemplate diving into this strange and mysterious world of algorithms and information. However, the information provided here will hopefully act as a nightlight for anyone wishing to learn about the scary nocturnal information monsters living in closets and under beds.

Ample Amounts Of Array

Arrays are the butter of the computer science world, because they are literally in everything! What is an array exactly? Well, it is just an ordered list. That simple? Yep, but sometimes there are lists inside of lists and these are called multi-dimensional arrays.

One-Dimensional Arrays

This is like a grocery list minus the nagging. They are great for storing a collection of data that is loosely or strictly related.

[sourcecode language="javascript"]
<p dir="ltr">var ingredientList = []; // create the array</p>
// now let’s fill it up
 ingredientList[0]="Butter";
 ingredientList[1]="Flour";
 ingredientList[2]="Rhubarb";

[/sourcecode]

So a quick breakdown shows us that we create a new array with the name “ingredientList”. Then we take the first slot in the array, index 0, and give it the string value “Butter”. Then we repeat this over and over again until we have a complete list. If you’re wondering why indexes start with 0, you’re not alone. I like to imagine it’s because no one wanted to hurt zero’s feelings by leaving it out.

Two-Dimensional Arrays

This is kind of like Martha Stewart’s new recipe book with each page containing a new list. A great use for this is more advanced ordering of simple data into a categorization system. Look here to see how to make one:

[sourcecode language="javascript"]
<span style="font-size: 1em;">var recipeBook = []; // create the array</span>

recipeBook[0] = []; // create a nested array
 recipeBook[0][0] = "Rhubarb Pie"; // mmm … pie
 recipeBook[0][1] = "Snicker Salad";

[/sourcecode]

Let’s break this down – anymore and we might have a death metal song. We see that in the first slot of the parent array we have inserted another array instead of just a string or number. This technique can be multiplied to the nth-dimension, but anything past the third dimension should be left up to Stephen Hawking, so try something else.

Just Enough JSON (JavaScript Object Notation)

If arrays are like butter, then JSON is like the wax paper that butter comes in. While the information it stores is not exclusively arrays they tend to go hand in hand and can be thought of as a collection of arrays, strings and numbers. They are great for storing document-style information. Although originally a JavaScript invention, it has spread like wildfire across the Web, acting as a lightweight information transport. Many Web applications offer other applications access to their data via this collection container. Let’s look at what this thing looks like:

[sourcecode language="javascript"]
// recipeBooks is actually an array of JSON elements
 var recipeBooks = [{
 // the curly brace is the start of a JSON element and vice versa
 "Martha Stewart's American Food": {
 "price": 10,
 "author": {
 "firstname": "Martha",
 "lastname": "Stewart"
 }
 }
 }, {
 "Pi": {
 "price": 3.14,
 "author": {
 "firstname": "Professer",
 "lastname": "Math"
 }
 }
 }];
[/sourcecode]

You’ll notice that nesting information is easy and still easy to read. This happens to be a list of recipe books with some information about them. It consists entirely of keys, the identifier to the left of the colon, and their values to the right. In order to access this information it is as easy as:

[sourcecode language="javascript"]
// turn into a javascript object
 var books = JSON.parse(recipeBooks);
 books['Martha Stewart’s American Food']['price']; // returns 10
[/sourcecode]

Wow, look at that! Nice, isn’t it? This is great for modeling information that should reflect real world logic.

Include Some Iteration

Iteration in example is reading over a recipe list and at each recipe doing something specific with that information, like deciding if you have it available or not. This is an invaluable tool for working with lists of information or collections.

Wrap With Recursion

When you see the word recursion, try to think of what happens when you face two mirrors toward each other. The light bounces back and forth between them and the mirrors get infinitely smaller. When we do this with data it allows us to create functions that call themselves within the definition – similar to Russian nesting dolls – but for this example we’ll say it’s like a cook book hidden within another cook book.

[sourcecode language="javascript"]
// accepts one parameters; data
 // data is a json element or array of json elements
 function iterate(recipeBooks) {
 var result = ""; // what we will eventually return
 // for each identifier key in the data
 for (book in recipeBooks) {
 // if it is a javascript object, aka json
 if (typeof recipeBooks[book] === 'object') { // recipeBooks[book] is the value
 // then repeat this process with the new value
 iterate(recipeBooks[book]);
 } else { // otherwise do this
 result += 'n' + book + ": " + recipeBooks[book]; // write it to a string
 }
 }
 return result; // a list of books
 }
[/sourcecode]

This can look scary at first, but if you read the step by step explanations it is really easy. Recursion can be used for many things, but most often it is used to process a collection with an unknown amount of elements. This is the basic idea behind recursion. It comes in peace.

Cooking Callbacks

Callbacks are the same as when you need to make pie, but before you can include the dough in the process of making it, you must first complete the process of making the dough. We do this with functions as well. Often we use the return value of one function to give another function context or variables to work with.

[sourcecode language="javascript"]
// define a function named making
 // accept a parameter of what to making
 // also accept a callback function to call when we’re done
 function making (dough, callback) {
 callback("making " + dough + "!"); // returns this value to the callback
 }

// call make() the item "dough"
 // when that function finishes it gives its return to the parameter greeting
 making("dough", function (action) {
 // then do something more with what you received
 console.log(action + "hungry for pie?"); // "Making dough! Hungry for pie?"
 });
[/sourcecode]

I can almost hear the locks in your brain clicking open as you realize what you can do with this recipe.

Eat All The Elements

Although JavaScript does offer many functionalities, the one it was originally intended for was dealing with what are known as DOM (Document Object Model) elements. These are what allow browsers to decide what HTML/CSS/JavaScript should combine to do. Until the recent switch to HTML5 it has been a hard going if you wanted to deal with the DOM without some sort of help, but now there are new and fun things to use.

While dealing with anything in the DOM you will need to query the document for the elements that you need to work with. We accomplish through built-in JavaScript functions like these:

[sourcecode language="javascript"]
<p dir="ltr">document.querySelector(".pie"); // query for one element of class pie
 document.querySelectorAll(".recipes"); // an array of all elements of class recipes
[/sourcecode]

Once you have this object there are limitless things you can do, but I am not going to go over each and every one so go ahead and search online for more information about the DOM.

Mmm …  Pie

I hope you learned something from this whirlwind bake-off tour. These items were picked because they are the basic building blocks – excluding syntax knowledge. When combined with what you already know, they should help relieve reliance on external libraries and kick-start you into creating some of your own homemade and scrumptious JavaScripts. Nom. Nom. Nom.