Douglas Crockford The Good Parts Examples

douglas crockford the good parts examples

No other book has had quite the impact on the JavaScript ecosystem as Douglas Crockford’s “The Good Parts.” The Good Parts is really a story of how enlightenment came to be on Mr Crockford. Now, Doug has been coding software for a long time, therefore it makes sense to listen to what he has to say. His main argument is that for all of it’s nasty flaws, JavaScript has some really good parts. If JavaScript has many good parts, but also some bad parts, does it not make sense to focus on and make use of the good parts? Indeed it does! This episode will do just that, and take a look at the parts of the JavaScript language that Douglas Crockford Champions. Let’s have a look, shall we?


Setting Up A JavaScript Development Environment

Getting started with JavaScript is arguably easier than in any other language from any timeframe. At it’s most simple, simply open up a web browser, and navigate to the JavaScript console. Google Chrome, Mozilla Firefox, and Microsoft Edge all have mature and excellent Developer Tools available for free built right into the browser. You could use something as simple as the following code to get started.


Objects According To Crockford

This section will take a look at how Doug presents objects in JavaScript and covers Object Literals, Retrieval, Updating, Reference, Prototype, Reflection, Enumeration, Delete, and Global Abatement.


Object Literals

It is very easy to create an object literal in JavaScript. Let’s a few examples.

You can command an object into existence with a line of code just like this.

Instead of creating an empty object, you could define an object and populate some values in one shot.

Cool stuff. Now, the left side of each key / value pair is referred to as the property. Each property should have some corresponding value, and multiple properties are separated by commas. You can also nest Objects very easily like so.


Getting Values From Objects (Retrieval)

Click To Retrieve Values! Clear

<div id=”valueretrieval”>

Here we make use of the convenient dot notation, however you can also access values using bracket notation if you prefer such as the following:

If you try to access a value on a non existent property, you will be returned undefined.

You can however check for an undefined value and fill in a default value if you like using the || operator.

Trying to get a value from an undefined value will produce a TypeError.


Functions

Functions are where the magic happens. According to Crockford, Functions are the best thing about the JavaScript language. Functions are linked to Function.prototype.


Creating a Function Literal

Let’s see an example of a function literal.


Four Invocation Patterns

There are four ways to invoke a function in JavaScript.

  • Method Invocation
  • Function Invocation
  • Constructor Invocation
  • Apply Invocation

Method Invocation

If a function is stored within the property of an object, then it can be thought of as a method. Here comes the confusion: The this keyword. The JavaScript this implementation is the most confusing and convoluted thing seen among any language that implements some form of this. When a method is invoked, the value of this is bound to that specific object. How do you know if you are calling a method? If you are using a refinement such as the . operator, then you are calling a method. Let’s see an example.

Click To Invoke a Method! Clear

<div id=”methodinvocation”>


Function Invocation

If a function is not a property on an object, then when it is invoked, it is done so as a function. A function that is invoked as a function has this bound to the global object, typically the Window object. Let’s verify this claim.

Click To Invoke a Function! Clear

<div id=”functioninvocation”>


Constructor Invocation

There are no classes in JavaScript, but you can create new object instances in a similar way to calling a construct method in more traditional object oriented programming languages. Oddly enough, getify makes a good point in that what is commonly referred to as object oriented programming languages should actually be referred to as class based programming languages. At this point, the terminology is too entrenched but if you think about it, it makes sense. In the classical OOP style, you create instances of objects that are based on classes! JavaScript does not work like this at all. In JavaScript objects are derived from other objects. Let’s see how.

Click To See Constructor Invocation! Clear

<div id=”constructorinvocation”>

With the Constructor Invocation pattern, you are able to create new instances of an object with the new keyword. With this approach, this is bound to the newly created object. Of all the approaches to invocation, the Constructor Invocation pattern may feel the most familiar to most classical OOP programmers. Make sure to always use a capital letter on the variable that stores the function constructor. This is how you can quickly determine when a variable is meant to hold a JavaScript constructor.


Apply Invocation

One mind bender about JavaScript is that functions can have methods. One of those methods is the apply method. What it does, is to allow us to provide an array of arguments to pass to the function, in addition to allowing us to specify which object should be referenced by this. The first parameter to the apply method is what this should be bound to. The second argument is the array of arguments to pass to the function. Let’s see it in action.

Click To See Apply Invocation! Clear

<div id=”applyinvocation”>

These are the basics of invoking functions and how it affects this. Your homework should be to read about this at the Mozilla Developer Network in addition to reading up on the new bind() method.


Arguments

When functions are called, the have access to a hidden arguments parameter. What it does is to count the number of parameters that were passed into the function, and provides access to those values. This is why you can write a function and not have to specify how many parameters it needs.

Click To See Arguments in Action! Clear

<div id=”arguments”>


Exceptions

Douglas Crockford doesn't need to use try-catch. When Douglas Crockford writes code, there are no exceptions. It turns out however, that JavaScript does provide an efficient means of handling exceptions. You are not Douglas Crockford, and as such may encounter errors. Learn how to deal with these exceptions with this example.

Click To See exceptions in Action! Clear

<div id="exceptions">


Recursion

Recursion can almost be thought of as a form of looping. A function can call itself to break up a problem into smaller subproblems. When all of the subproblems are complete, the recursion has run it's course. JavaScript does not have tail recursion optimization. What that means is that if you screw up the logic in your recursive function, you very well could crash the programming environment by exhausting the return stack. Here is an example of the Towers of Hanoi puzzle solved with recursion.

Click To See recursion in Action! Clear

<div id="recursion">


JavaScript Scope

Scope in JavaScript is a beast, especially if you are used to scoping rules from other languages. So just what is Scope? Well, it's where to look for things. It's not really much more complicated than that. In JavaScript, we have function scope. Let's take a look at an example.

Let's walk through this, because it's crazy.

First up we'll tackle the compilation phase.

  • 1. Hey global scope, I have a declaration for a variable called fact. The global scope says, "I got it, you can move on now".
  • 2. Hey global scope I have a function called roundhouse(), and I want to register him in the global scope. Global scope meets this request and roundhouse() is now registered in the global scope.
  • 3. We now descend into the roundhouse function and we say, hey roundhouse scope, I have a declaration for the variable called fact. Function scope roundhouse now has this variable declared.
  • 4. We are still in the scope of roundhouse(), and we now come across a jslint() function. So what happens? Hey roundhouse() scope, I have a function declaration for function jslint(). Scope of roundhouse() replies back and says great, I've got him registered.
  • 5. We now descend into the jslint() scope. Hey scope of jslint(), I've got an implicit variable declaration for fact. Scope of jslint() responds back and says ok, you've got your fact variable declared.

Now, just milliseconds later, we go through the execution phase.

  • 1. Hey global scope, I have an LHS (Left Hand Reference) for a variable called fact, ever heard of him? Global scope responds, "Yep I sure have, here is the reference to that variable". At that point the value of 'Doug Crockford can go back in time like superman, as he did with ES4 to make ES5.' is immediately assigned to the fact variable in the global scope.
  • 2. At this point during the execution phase, we jump right down to the call to roundhouse(). The lines above that were taken care of during the compilation phase.
  • 3. Hey global scope I have an RHS (Right Hand Reference) for a variable called roundhouse, have you heard of him? Global scope responds, "sure, I got him, here you go - here is a reference to that variable." Now, we can retrieve that value and we find that it is a function object. We also see that roundhouse is immediately followed by the innvocation operator so we execute that function.
  • 4. Hey scope of roundhouse(), I have an LHS reference for a variable called fact, have you heard of him? The roundhouse scope responds back, "I sure have heard of him, here is the reference to that variable." Now do note, this is the fact variable that lives in the roundhouse scope, *not the global scope*! With that, the value of 'Douglas Crockford doesnt sleep, he waits to be triggered.' is assigned to the fact variable in roundhouse scope.
  • 5. At this point we skip down to the call to jslint() and it goes a little something like this. "Hey scope of roundhouse(), I have an RHS reference for a variable called jslint, have you heard of him? The roundhouse() scope responds back, "Yep, here is the reference to that variable." We then find his value, and find it is a function object and then immediately execute it.
  • 6. We then move into the scope of jslint() and the conversation goes like this. Hey scope of jslint() I have an LHS reference for a variable named fact, have you heard of him? The scope of jslint() responds back and says, "Yes indeed, here is the reference to that variable." This is true because fact was declared as a named parameter. At this point the string 'If you execute "typeof Crockford" your browser will return "awesome"' gets assigned to fact in the scope of jslint().
  • 7. Now we move to the next line and we say, hey scope of jslint, I have an LHS reference for a variable named amazing, ever heard of him? The scope of jslint will respond with, "I've never heard of this variable amazing you speak of, go fish." What this means is since this scope does not have what you are looking for, go look in the next scope. So that is just what we do. Hey scope of roundhouse(), I have an LHS reference for a variable named amazing, ever heard of him? The scope of roundhouse will now respond with, "I've never heard of this variable amazing you speak of, go fish." Ok, let's keep going. We are now in the global scope. Hey global scope I have an LHS reference for a variable named amazing, ever heard of him? The global scope will now respond with, "I've never heard of this variable amazing you speak of but since I like you, I will create one for you as if by magic, here is your reference to that variable". Just like that, you have created a new variable in the global scope, that you may have not intended to.

Click To See scope in Action! Clear

<div id="scope">


Closure

Closure depends on Lexical Scope. In order to actually understand closure, you must first understand lexical scope. Lexical scope is the understanding of declaring variables within their given scope, and is set in stone upon compilation. Lexical scope states that variables that belong to this function scope, do not belong to that function scope. The author of the software makes the decision ahead of time which variables will belong to which scope.

So what it Closure? The definition by getify is the one that sums it up best.

Closure is when a function remembers its lexical scope even when the function is executed outside that lexical scope.

I know we dedicated this article to Crockford, but Getify just might be the next Crockford - so we gotta get with the times. Let's look at some example code.

Here we have an outer function named crockford(), and he has a variable named fact in his scope.

There is an inner function named nunchucks() which has it's own scope bubble, which lives inside the scope bubble of crockford(), it is a nested scope.

We then take a reference to the function nunchucks() and pass it as a parameter to a swing() function which lives outside of the scope bubble of both nunchucks() and crockford().

When the nunchucks() function on line 12 executes outside of the scope where it was defined, it still has access to the variables contained in the lexical scope where it was originally defined. This is in fact closure.

Click To See closure in Action! Clear

<div id="closure">

Let's check out another example of closure. This one is from The Good Parts Book.

Let's see how this code is an example of Closure. We begin by calling the fade() function and pass in a dom element. fade() sets it's level to one and defines a step() function. fade() then calls the setTimeout() function with the step() function as the first parameter, and 100 milliseconds as the second. The fade() function returns, and it has finished executing. fade() is now done.

100 milliseconds later, step() gets invoked again. In order to do it's work, it needs to have access to the level variable which belongs to the fade() scope. Remember, fade() has already executed and returned, it is a memory at this point. It's variable level however lives on, as long as the inner function step() needs it to do it's job. Check out this Crockford Good Part Example:

Click To See closure2 in Action!

<div id="closure2">

Douglas Crockford can read your mind with a five liner closure


Callbacks

Callbacks are also known as higher order functions. This is to say that a callback, is a function which is passed to another function as a parameter, and that passed function is then called or executed inside the function it was passed to, usually after a condition is met, or after a set period of time. It is very popular in JavaScript, so much so that we refer to it as the callback pattern.

Let's see an example where we set up two functions. First we create a callbackfunction() which outputs some text to the screen when it is executed. Then we create a firstfunction() which we pass two parameters. The first parameter is some text as a message which firstfunction() will use to output to the browser. We also pass callbackfunction as the second argument to firstfunction(). Finally, we attach a click event to a button to execute the firstfunction() when clicked. Check out the results.

Click To See callback in Action! Clear

<div id="callback">

You'll note the only function we as the user actually triggered was firstfunction(), however both the output of firstfunction() and callbackfunction() appear on the screen thanks to the callback pattern. This is the very basics of a callback, and it is worthy of entire articles on it's own. The takeaway however is that when you pass a function as an argument to another function, you are making use of a callback.

Callbacks can be a little tricky so let's see one more example.

Click To See callback in Action! Clear

<div id="callback2">


Modules

The classic module pattern is one of the most used patterns in all of JavaScript. It has a couple of characteristics that actually make it a module. The first characteristic is that the module must have an outer wrapping function which gets executed. The second characteristic is that there has to be a least one inner function that gets returned out and keeps a closure over the internal state. The purpose of the module pattern is to provide a mechanism to emulate traditional class based programming concepts by offering the ability to include public and private methods and variables inside a single object, which allows you to determine what information you would like to expose to consumers of the module.

This pattern makes use of closures to provide this idea of privacy and state. You should only return the public API of the module, leaving all other methods and variables private inside the module. We can see how this might be confusing! Before you can understand Modules, you need to understand Closures. Before you understand Closure, you need to have Lexical Scoping down cold. So if it doesn't click right away, go back and review Lexical Scoping, then Closure, then revisit Modules. Let's see an example.

Click To See Modules in Action! Clear

<div id="moduleex">

There is *a lot* more to modules, but this section gave us an idea of what the module pattern in JavaScript is used for and how we might construct our own modules.


Delegation

This part was going to be called Inheritance, but the truth is, in JavaScript this mechanism is much more delegation based than inheritance based. The key idea is that objects in JavaScript do not so much have inheritance, as much as they have Linkages to a prototype. JavaScript has no classes, and therefore you might wonder how you could even do object oriented programming. Well, in JavaScript, objects link back up the prototype chain. All objects in JavaScript are created by a constructor function. This new object is not based on the prototype, it is linked to the prototype. Recall lexical scoping where if you have an inner function for which the compiler can not find a reference to a variable in it's scope, it will move outside of it's bubble so to speak to the next outer level, and request that outer scope for a reference to that variable. This continues until finally the global scope is reached, and if there is no variable reference there, then one gets created (in non strict mode).

Every single object in JavaScript is created by a constructor function. Any time a constructor function is called, a brand new object is created out of thin air. It is not an object in the way you would think about in terms of classical object oriented programming, but rather an object that links back up to it's own prototype. Let's see how this works in an example.

Click To See delegations in Action! Clear

<div id="delegationex">

Before this code even runs, there are a few things that happen automatically in JavaScript. First, there is a function named Object. There is also an object that this function is linked to which is called Object.prototype. Those two resources need to be read in their entirety to understand what is happening in the example code above. In fact, the concept of object orienting needs an entire article or even book to cover completely. All we want to understand here is that when a method is called on an object, if that particular object does not have the method in question, it will then start going up the prototype chain to find an instance of that method. This is in direct contradiction to how traditional classes hand down methods to their children. In JavaScript, objects check their prototype linkages, they do not look to a parent class for their functionality. So when we see the call to Person1.greet() and Person2.greet(), we can see that those functions makes use of a myname() function. Neither the Person1 or Person2 object has a myname() function defined on them. So what happens in this example when they execute, is they need to move up the prototype chain to find that myname() function. Since each Person object has a link to Person.prototype we can see that the prototype does indeed have a function named myname(). So we can say that these new objects are delegating the responsibility of calling the myname() function to their prototype. It's kind of like saying, "Hey buddy, I'm trying to complete this task and I don't know how to do it, can you give me a hand?"


Arrays

Douglas Crockford refers to Arrays in JavaScript as an object that has array-like features, as if to say it is not really an array. The reason for this is because JavaScript converts the array subscripts into strings, and those strings become properties on the object. Getting and Setting values to and from arrays works just like getting and setting values in objects. Let's see how to create an Array Literal here.

Click To See arrays in Action! Clear

<div id="arrayex">

As you can see we can assign any type we like to an array slot. In our example we place a string, function, object, number, a couple of booleans, an array, null, undefined and NaN into our array. In one of the quirky effects of JavaScript, if you apply a typeof operator to all of these, you can see that almost everything is an object, save for NaN which is actually undefined. JavaScript!

The length property is quite handy in JavaScript and is often used in loops. Let's see how.

Click To See array.length in Action! Clear

<div id="arrayex2">

JavaScript also has a for in loop construct but Douglas Crockford makes a case for sticking with the standard for loop which exists in all C-based languages. The problem with for in is that it may produce results in an order you don't expect, or it may pull in unexpected properties from the prototype chain. The for loop is a good part.

Arrays and Objects are so closely related in JavaScript that it can be confusing when to use one or the other. Doug gives us this handy rule:

When the property names are small sequential integers, you should use an array. Otherwise, use an object.Douglas Crockford

JavaScript Methods

JavaScript has a small collection of methods built into the language that will make your development easier. In a language like PHP, you have literally thousands upon thousands of functions built into the language. In a sense, PHP is it's own framework. JavaScript has no such massive collection of built in functions. Perhaps this is why there are more JavaScript frameworks than you could ever imagine. People are trying to build into the language all of the richness of features that are required for web development. In any event, it will do you much good to be familiar with the built in methods of the language. Here are the links to the ones you want to know.

Douglas Crockford The Good Parts Examples Summary

This JavaScript Tutorial was focused loosely on the teachings of Douglas Crockford in his now famous book JavaScript The Good Parts. We had a good time reviewing some important concepts such as Object Literals, Getting Values From Objects, Functions, Creating a Function Literal, Four Invocation Patterns, Method Invocation, Function Invocation, Constructor Invocation, Apply Invocation, Arguments, Exceptions, Recursion, JavaScript Scope, Closure, Callbacks, Modules, Delegation, Arrays, and JavaScript Methods.