Douglas Crockford. JavaScript: The Good Parts. Unearthing the Excellence in JavaScript.
O’Reilly Media / Yahoo Press, 1st edition, May 2008.
ISBN-10 0-596-51774-2, ISBN-13 978-0-596-51774-8.

Chapter 1: Good Parts

Chris O’Dell, 15 October 2012

Throughout this chapter Crockford is trying to get across that JavaScript is a language that is full of ‘bad parts’, but also some very ‘good parts’ and if you can avoid the ‘bad parts’ then you’ll have a rather enjoyable experience.

He states that the language was not subjected to the rigours of a standards committee when lumped into Netscape Navigator 2, but due to the failure of Java Applets it became the “Language of the Web” by default.

Crockford believes that the reason many people find JavaScript painful is due to the extremely poor API of the browser, the Document Object Model (DOM), rather than the language itself which would be difficult to work with regardless of the chosen language. Also, Web Developers are forced to use JavaScript, due to a lack of alternatives, so this is also the cause of much frustration.

My Kindle copy has 89 highlighters on the line “The very good ideas include functions, loose typing, dynamic objects, and an expressive object literal notation. The bad ideas include a programming model based on global variables.” Hopefully we’ll get to grips with these good ideas throughout the book.

Crockford states that the language has very little to do with Java and has more in common with Lisp and Scheme - he calls it Lisp in C’s clothing. As someone who hasn’t programmed in either I will have to take his word for it and defer to you guys to corroborate his statement.

JavaScript uses Prototypal inheritance, which is unfamiliar to classically trained developers - I know that I have struggled with this is in the past and I’m hoping this book can clear it up for me.

The standard which defines JavaScript is the third version of ECMAScript which the book will stick to as this will avoid many of the ‘bad parts’ of JavaScript.

He also gives an overview of the appendices and unlike some appendices, which tend to be listings, I feel that it may be worth our while to review these too.

Chapter 2: Grammar

Ian Bruntlett, 22 October 2012

This is a brief chapter, about grammar.

In particular it looks at the good bits of JavaScript and gives an overview of its grammar, using railroad diagrams.

I’m not a JavaScript expert but this chapter looked OK to me.

Chapter 3: Objects

Frances Bountempo, 29 October 2012

Objects

Simple types are numbers, strings, booleans, null and undefined. Everything else is an object, eg functions, arrays, regex.

Simple types are immutable. Objects are mutable keyed collections.

Keyed collections = container of “properties” = has a name and a value.

JS uses “prototype linkage”

Object literals

var empty_object = {};
var storage = {
    "first-name": "Jerome",
    "last-name": "Howard"
}

You might not need to quotes. Objects can nest.

Retrieval

Use [] or the . Notation to get the value back. Undefined is returned if it’s not there

storage["first-name"] //"Jerome"
storage.name //undefined

Attempting to retrieve values from undefined will throw a TypeError exception.This can be guarded against with the&& operator

Update

storage["first-name"] = "Jerome";

This replaces existing values or add new ones.

Reference

Objects are passed by reference
var x = storage;
//change one changes them both

Prototype

Using {} for object literals linked them to Object.Protoype (a standard object in js) He suggests a create method:

if (typeof Object.create !== 'function') {
   Object.create = function (o) {
     var F = function () {};
     F.prototype = o;
     return new F();
  };
 }

var another_storage = Object.create(storage);

The prototype link is used for retrieval. “Delegation” is used to walk the chain of protoype’s prototypes to find the property requested.

The prototype can be changed dynamically.

Reflection

Typeof tells us “undefined” if the property we ask it of doesn’t exist. You might want to discard “function” types when you reflect.

You might prefer to use hasOwnProperty, to avoid the prototype chain.

Enumeration

For … in … loops over all the properties in an object, including functions and prototypes: use hasOwnProperty to remove things from the prototype and typeof to discard functions.

To enumerate in a known order, a for(i=0; i<properties.length; i+=1) loop may be better.

Delete

delete storage.name This deletes a property if it has one, but not prototypes. “Removing a property from an object may allow a property from the prototype linkage to shine through.”

Global abatement

[Aside: ‘abatement’: The ending, reduction, or lessening of something. From Latin: ad “to” (see ad-) + battuere “to beat” Also related to slaughter, eg abattoir]

It’s easy, but bad, to have global variables. He suggests having one global variable, which you chuck all your other global variables in, as properties. At least they are in one place then. We are promised closure for information hiding in the next chapter.

What have we learnt?

  1. Prototype linkage can cause you confusion. On accu-general, Richard Harris mentioned being familiar with this from other languages. I’ve not come across it before. What about anyone else?

  2. Objects are just “property bags” - dictionaries using strings as keys. So we’ll find out “arrays” are not arrays.

  3. Globals are evil. … but somewhat unavoidable in js. But you can be tidy.

Chapter 4a: Functions

Matthew Markland, 5 November 2012

Chapter 4 is all about functions. I think the first statement is a good summary:

“The best thing about JavaScript is its implementation of functions.”

As noted previously, functions are themselves objects. They are linked to the global Function.prototype object and have two hidden properties: their context (environment), and their code. Functions also have a “prototype” property which contains an object which has a “constructor” property which is the function itself. Crockford notes that he’ll expand on this somewhat strange construct in the next chapter. What makes a function object different is that it can be invoked.

The function literal syntax looks pretty standard to me. You can define nested functions and the inner function has access to the outer functions context (locals, etc).

As mentioned, what makes function objects different is that they can be invoked. JavaScript uses the (arguments) form to invoke a function. an invoked function receives two additional parameters beyond those listed; the “this” parameter and the “arguments” parameter. The invocation may pass any number of arguments; any argument that maps to a parameter will be passed in that parameter. If you pass fewer arguments than the function has parameters, the unbound parameters will be set to “undefined.” If you pass more arguments than parameters, you can access the additional arguments via the “arguments” array (more on this later). Parameters are not type-checked.

The value of the “this” parameter is determined by the invocation pattern used. There are four patterns:

Method invocation refers to the invocation of a function stored as an object property. Functions such as these are called methods and have the “this” parameter bound to the object the function is called against.

Function invocation refers to the basic, plain function call. The “this” parameter is bound to the global object. This fact makes it more difficult for a method to use inner functions as the “this” parameter for the inner function does not bind to the object the method is called on. An idiom for working around this is for a method to define a local called “that” which has the “this” parameter assigned to it. The inner function can then use “that.”

Constructor invocation refers to using the function to construct a new object. Crockford takes a moment here to reiterate that JavaScript is a prototypal language, which is expressive in its inheritance structures but not as widely understood. He also notes that the syntax of the constructor invocation closely models what one might expect in a classical (uses classes) inheritance language, which muddies the waters. Constructor invocation uses the “new” prefix and causes a new object to be created with a hidden link to the function’s “prototype” property. The “this” parameter is bound to the new object. Constructor functions start with a capital letter by convention. Calling a constructor function without the “new” prefix operator can cause weird things. He illustrates the use of a constructor and mentions that he doesn’t recommend the style show. I’m guessing there will be more details in the chapter on inheritance.

(Interjection: at this point I’ll just throw in that this construction idiom seems to be the most confusing thing I’ve run into so far. I’m still not groking it as of yet.)

The final invocation pattern is the apply invocation. Since functions are objects they may have methods also. A method available to functions (I’m guessing via Function.prototype) is the “apply” method. The apply method allows you to create an array of arguments and a binding for this and the call the function. It also appears to allow you to apply object methods to objects that aren’t in the inheritance chain as long as they have the correct properties.

The “arguments” array mentioned previously gets its own little section. Basically the main detail is that it isn’t a true array in that it does not support all of the array methods.

Function returns gets its own little section. Basically all functions return a value. If the function is invoked with the constructor idiom (i.e. with the “new” keyword) and the return value provided by the function is not an object, the “this” parameter is returned instead.

Chapter 4b: Functions

Matthew Markland, 12 November 2012

When last I wrote we were in the middle of Chapter 4 discussing functions. We’ll start right in on exceptions.

Exceptions

In general, I didn’t see anything too remarkable here compared to C++. The main differences appear to be the fact that you need to create an exception object with the “name” and “description” properties, and the fact that there is only a single catch clause. If you want to differentiate your catch behavior, you have to inspect the exception object that is caught and use one of the properties.

Augmenting Types

Augmenting types takes advantage of the fact that you can modify a type’s “prototype” property and have that change affect all instances of the object. Using this, you can improve the expressiveness of the language by providing syntactic sugar. He gives an example of this which seems fairly straightforward. He notes that care must be taken when mucking about in the public/global objects. He suggests using the a pattern where you conditionally add the extension so you don’t overwrite any existing behavior.

Recursion

Used a lot due to the tree-structure of the DOM. But, there is no tail call optimization so you can blow out the stack if you aren’t careful. No real surprise there.

Scope

Here I think is one of the tricky spots. Even though JavaScript has blocks like other C-style languages, it does not have a block scope. There is function scope which contains parameters and variables defined in the function. These are not visible outside of the function scope, but are visible to everywhere within, which means they are visible to inner functions. Using this to the developer’s advantage was discussed some earlier. Crockford recommends declaring all variables used in a function at the top of the function body.

Closure

Closure is a language feature that allows a function to have access to the context in which it is created. I think the examples are key if you aren’t used to the concept. One thing I found bothersome, especially with the example on the bottom of page 39 was the choice of indentation for the pieces. I think that is just me needing to get used to idiomatic JavaScript, but I found it hard to see the function definitions and applications. I think this is an important section to understand going forward, though.

Callbacks

Here Crockford seems to be presenting the callback idiom to support asynchronous handling of events, and the fact that JavaScript having functions makes this easier. I know that some JavaScript libraries/frameworks (node.js for sure I think) base a lot of their design on asynchronous callbacks.

Module

Here functions are used to present an interface but hide its state and implementation. In essence, something more like the class based objects many of us are more familiar with. One important use of this idiom is to use functions to produce modules that hide global state/variables.

Cascades

Another idiom that allows chaining of function calls by returning “this” rather than leaving the return value “undefined.” Allows for more expressive interfaces.

Curry

An idiom that will be familiar to users of functional languages where you produce a new function by combining a function and an argument. Crockford presents an augmentation of Function which adds a curry method that can be used to simplify the creation of curried functions using closures.

Memoization

Here functions use objects to remember the results of previous operations so that they don’t have to repeat calculations. The fibonacci example is a classic. :-) Again, Crockford shows the usefulness of extending the syntax by creating a memoizer function that simplifies the creation of memoized functions.

Overall this chapter points out a lot of interesting idioms and shows off a functional side to JavaScript. Crockford’s examples where he builds up more complicated behavior by creating functions that produce other functions are powerful and enlightening. It was also interesting to see how functions can be used in surprising ways to create containers for globals (i.e. modules) when the language doesn’t give you the other tools you might want for this. All in all the chapter definitely shows the good and the bad, but more good than bad.

Chapter 5: Inheritance

Mick Brooks, 26 November 2012

This chapter starts by introducing prototypal inheritance, where objects inherit directly from other classes. This is less familiar to most of us than classical inheritance, where objects are instances of classes which then inherit from other classes.

(I’m forever stumbling on the pronunciation of prototypal. Prototypical just seems more natural to me. To try and get over it I followed the Alyssa P. Hacker pattern from SICP and started saying Prototype Al in my head. It made it worse. I still stumble on Prototype Al, but now I stumble on classical too: Classic Al makes me think of The Fonz.)

The author compares the use of inheritance in classical languages and Javascript. He asserts that inheritance provides two services in classical languages: code reuse and type-hierachy. As Javascript is loosely typed, the type-hierarchy service is redundant, leaving only code reuse. This left me a little uneasy, as inheritance for code reuse is generally discredited in classical languages. I’ve learned to prefer composition over inheritance. What we learn here is that Javascript’s loosely-typed, prototypal behaviour is sufficiently different from classical languages to support many different inheritance and code reuse patterns.

I’m tempted to remind myself why we prefer composition over inheritance, and to check how the reasoning is different for Javascript. Is it different because of differences of typing, because of prototype-based programming, or both? Oh, and any ideas what the author means by loose typing here? I’m somewhat familiar with static vs dynamic typing, and strong vs weak typing. Where does loose typing fit in?

Pseudoclassical

Pseudoclassical is the first inheritance pattern we’re shown. With the constructor invocation with new, and the constructor property that’s set on every Function object’s prototype, it’s somewhat built in to the language. That doesn’t mean it’s the best pattern. We’re shown that it’s something like a confused attempt to make prototypal inheritance look like that of classical languages.

I found parts of this section hard work, I think mainly due to confusion about whether the word object refers to the constructor function (which, like everything else, is an object) or to the new object we hope to construct with it. After a few reads I think I managed to keep it straight, and the example helped.

Another confusion I had was thinking that every object has a prototype property. All objects have an internal reference to a prototype object, but it’s not accessible directly. A Function object has both this internal reference to its prototype, and a prototype property. Its prototype property doesn’t point to its own prototype, but to the object that will be set as the internal prototype of any objects constructed by using new with the function. Confused yet? See the diagram I made at http://sinking.in/images/prototype.png.

There’s one snippet of code in the example on page 47 that seems too tricky to me:

return (typeof other === 'object' && other) || that;

The mixture of types in that expression just seems odd:

(boolean && object) || object.

Am I being too classical when I judge that as a misuse of shortcircuit operators? I’d have thought that

return typeof other === 'object' ? other : that;

is better all round, or have I missed something? Finally we’re told about a serious design error in the language. Fail to use new when you invoke a constructor function and this will be set to the global object, and so it stomps over names in the global scope rather than creating a fresh object. Despite a convention of using an initial capital letter for, and only for, constructor functions, this is enough of a problem to consign this pattern to the Bad Parts of Javascript. There are better code reuse alternatives we should use.

Prototypal

The first alternative is Prototypal inheritance. It completely ignores the invocation expression with new, and relegates the use of constructor functions (with an initial capital) to an implementation detail of Object.create (which was introduced in Chapter 3). As such, we never type prototype in our own code. Instead, our (lowercase initial letter) constructors are just regular functions that return objects.

Functional

The final alternative is Functional inheritance. If I’ve understood it correctly it’s just Prototypal inheritance extended with the Module techniques we saw in Chapter 4 to make the object’s innards private: until now they’ve been public for all to see, play with, and break.

A template for a functional constructor is shown which allows for truly private variables and functions together with variables and functions that are shared with other constructors in the inheritance chain via an argument named, presumably by convention, my. my brings to mind protected visibility in classical languages, but it’s more than that: not only can the child constructor see its parents’ my bits, we could also arrange for the parent to see the child’s my bits. None of the examples use my and I’m not clear on the best way to make use of it, so I’ll be looking out for it in future.

Another thing I think is worth highlighting is a trick that accesses one public method from another via a private variable. That way, even if a malicious/clueless user replaces the first public method on the resulting object, the other methods that use it will continue to access the original method. The techniques shown prevent your object’s innards leaking out even if a user tries to replace its methods with spy functions. They can break your objects but they can’t get at your secrets. The author calls an object that is so protected durable, and says that each method on such an object is a capability. I’ve not heard those terms before, and I would be interested to learn if they’re terms from previous literature or are inventions of the author.

Other bits

Elsewhere the chapter talks about object specifiers as a way to make constructor arguments friendlier: they effectively provide named parameters with defaults. The final section talks about a technique for composing the behaviour of an object from a set of Parts. We’ve already seen how we can add a method to any object. Parts extend this to a function which adds a related set of methods that share state amongst themselves. I don’t know a lot about Mixins, but it looks very similar.

Conclusion

This chapter did a good job of showing the problems with the naive approach to inheritance that a classical programmer might take. It then demonstrates some alternatives, working up to the Functional pattern, which feels like it should be the preferred option for creating new objects. The author points out that more complicated constructions are possible, but it seems like this pattern is aimed at a sweet spot between encapsulation, reuse and complexity. It feels like a good foundation for starting to work with objects in Javascript. I once tried to understand how jQuery was put together and failed. I feel much better equipped now.

Some of the comments on classical programming seem odd, and in particular this sentence is wrong: “In classical languages, class inheritance is the only form of code reuse”, and so I’m not sure what to make of the comparisons made between Javascript and other languages. That said, I’m not reading this book to learn classical programming. As a Javascript novice I can’t really comment on the accuracy of the Javascript advice, but it seems solid enough.

Chapter 6: Arrays

Mike Long, 3 December 2012

Chapter 6 is all about Arrays. Like most other parts of the language, array literals look just like you would expect. Only below the surface there is a completely different implementation approach. For instance if you specify the array with key-value syntax, even with numbers for the key, the array inherits from Object.prototype instead of Array.prototype. Fun.

There can be empty elements in the array, and the length is not the number of elements in the array, but the index of the last item +1. You can delete items at the end of an array by setting the length property to less than the current length. You can also delete elements by using the delete operator, but this leaves holes in the array. So the best way is to use splice.

Arrays are normally iterated over by using the traditional for loop syntax. To find out if an object is an array you can define an is_array method. You can also augment the Array prototype to add arbitrary functionality to arrays. I like this. With this functionality it is easy to add the dimensioning and matrix methods described.

I quite enjoy the writing style, but it might be the densest technical book I’ve read since K&R. Definitely one to read through a couple of times. I got off lightly with this little chapter :-)

Chapter 7: Regular Expressions

Peter Hammond, 10 December 2012

Regular expressions are a built in feature of Javascript, borrowed from Perl. Several string methods (covered in chapter 8) can use regexes. Regular Expressions have a complex and somewhat arcane syntax, so they are hard to write and more importantly read, which is not helped by Javascript not permitting comments or whitespace in them.

A regular expression in Javascript is delimited by forward slashes (which confused me the first time I saw it). The book shows an example regexp to parse a URL:

var parse_url = /^(?:[A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#*))?(?:#(.*))?S/;

which I think neatly illustrates the point about terseness and complexity; the ’?’ has three different meanings in there, ‘^’ and ’:’ two each. The book uses a railroad diagram (like the ones used to describe the language syntax) to describe the regexp. I am not entirely sure that helps but I may well give it a go next time I have one to explain. I will not go through the entire explanation of the expression, but the book does a good job of breaking it down in to digestible factors.

While going through the factors, Crockford notes that - “sloppy regular expressions are a popular source of security exploits” - the implementation of regular expressions is the least portable part of the language between Javascript processors.

As well as the regexp literal, there is a RegExp constructor which can build one out of a string, which should only be used where the string must be constructed at runtime, since the escaping rules make the expression even more obfuscated. There are three flags that can be appended to a regexp literal, g (global), i ( case insensitive) and m (multiline); it turns out in the next chapter that their meanings vary slightly according to what method the expression is used in.

The chapter finishes with a summary of the elements of regular expressions: choice, sequence, factor, escape, group, class, class escape and quantifier.

See also Verity’s secret shame revealed.

Chapter 8: Methods

David Sykes, 17 December 2012

This chapter details a variety of standard methods that are available on the standard types.

Array functions

array provides the following methods:

array.concat(item...)
returns a new array with the supplied items concatenated to the end of a shallow copy of the original. If any of the items are arrays then the array contents are appended, which might be a little non intuitive.

array.join(separator)
concatenates the contents of the array into a string with each element separated by the supplied separator string. For joining large numbers of strings this method is considered faster than adding the items with the ‘+’ operator

array.push(item...)array.pop()
These functions allow an array to be treated like a LIFO stack, pushing one or more items on the end and popping the last item off.

array.shift()array.unshift(item...)
These functions ‘push’ or ‘pop’ items from the beginning of an array. Together they could be used to create a LIFO stack, though they are generally a lot slower than push and pop. Unshift with push would create a FIFO stack.

array.reverse()
Unsurprisingly reverses the order of elements in the array. It modifies the array, and also returns the array.

array.slice(start, end)
This creates a shallow copy of a section of the array, including elements from start up to, but not including, end. If end is omitted the section goes to the end of the array, and if either parameters are negative then the array length is added to give a position relative to the end of the array.

array.splice(start, deletecount, item...)
This function removes a block of entries from an array and replaces them with another block, returning an array containing the removed items.

array.sort(comparefn)
Sorts the contents of the array. The default sort is to treat the contents as strings.to sort ints or other objects a comparison function will be required. The comparison function can be any function that takes two arguments, and returns 0 if the items are the same, a negative number if the first parameter should come first, or positive if it should come second.

Function

Function has a single method: function.apply(thisArg, argArray) This invokes the specified function, passing in the object that will be bound to this together with an optional array of arguments. Chapter 4 uses the apply method.

Number functions

Number implements a range of functions that help with handling them:

number.toExponential(fractionDigits)
Convert to an exponential format with the specified number of decimal places, between 0 and 20

number.toFixed(fractionDigits)
Convert to a fixed decimal form with the specified number of digits

number.toPrecision(precision)
Convert to a decimal form with the specified digits of precision

number.toString(radix)
Convert to a string using the optional radix, or base, value. If the radix is omitted then 10 is assumed.

Object function

Object implements a single function:
object.hasOwnProperty(name)
Checks the object for the named property without checking the prototype chain, returning true if the property exists

RegExp functions

RegExp was covered in chapter 7, and for me that chapter was worth the cost of the book by itself. This chapter summarised briefly the exec and test methods.

regexp.exec(string)
This matches the regexp and the string and returns an array in which the first element is the matched part of the string, and the subsequent elements are the captured groups.

Specifying the g flag in a regular expression makes things more complicated, but it basically allows a string to be repeatedly queried for a regular expression.

regexp.test(string)
The simplest and fastest of the regular expression functions, this returns true if a match was found

String functions

string.charAt(pos)
Returns the character and position pos in a string, or the empty string if pos is not a valid position in the string. As JavaScript does not have a char type a string is returned.

string.charCodeAt(pos)
Returns an integer representation of the code point value of a character in the string

string.concat(string...)
Concatenates strings together. Rarely used as the + operator is more convenient.

string.indexOf(searchString, position)
Searches for searchString within the string, starting from the optional position value, and returns the position of the first match, or -1 if no match is found.

string.lastIndexOf(searchString, position)
The same as indexOf, but searching from the end of the array.

string.localeCompare(that)
Compares two strings in an unspecified way. The examples given suggest that lower case is less than upper case, and shorter strings are less than longer strings, but as the comparison is unspecified I would assume this should not be relied upon.

string.match(regexp)
If the regular expression does not include the g flag then this is the same as regexp.exec(string). If the g flag is specified then an array is returned that contains all of the matches, but excluding the capturing groups.

string.replace(searchValue, replaceValue)
Search for instances of searchValue and replace them with replaceValue. If the search value is a regular expression with the g flag then all occurrences are replaced, otherwise only the first occurrence is replaced.

replaceValue can be a function, in which case he function is called for each match with the matched text and groups as parameters, and the returned string used as the replacement.

If replaceValue is a string then the $ character implements a set of macros that allow various areas of the matched text to be referenced.

string.search(regexp)
Acts like indexOf, but locating a regular expression rather than a string.

string.slice(start, end)
Makes a new string from a portion of the supplied string. Negative values can be supplied for values relative to the end of the string

string.split(separator, limit)
Splits the string wherever the separator is found, and return an array of the pieces. The separator can be a string or regular expression, and limit limits the number of pieces

string.substring(start, end)
The same as slice, but negative values are not valid. Not much use.

And finally some routines to change the case of a strings contents

Chapter 9: Style

Ed Sykes, 14 January 2013

In this chapter douglas talks about coding style and how important it is. I agree. He claims that good style helps you to understand and further modify the code. Style matters in the same way that good writing matters. He then talks about some elements of his own style and asserts that the style is consistent in the code examples.

A lot of the style is fairly standard stuff. Some are particular to JavaScript. Interesting he puts a space between an ‘if’ and ‘(’. With JavaScript’s treatement of functions as first class objects this seems like a useful convention as it does help with visually identifying function invocations.

He always uses scope blocks around if statements. He uses K&R style block scoping. He uses comments sparingly, using the code to illuminate meaning. Due to JavaScript’s lack of real block scoping all variables are declared at the top of the function. He illustrates a change in his opinion on switch statement fallthrough with a story about a bug.

A single global variable is used to contain applications or libraries. This prevents clashes with other libraries or applications.

Chapter 10: Beautiful Features

Frances Buontempo, 21 January 2013

In which our author describes “Simplified JavaScript”… just the good stuff

  1. Functions as first class objects i.e. lambdas with lexical scoping I’m not sure what that means, but the internet suggests static scoping rather than dynamic
    http://stackoverflow.com/questions/1047454/what-is-lexical-scope
    http://c2.com/cgi/wiki?LexicalScoping

  2. Dynamic objects with prototypical inheritance Objects are class-free. Add new members by assignment. An object can inherit members from another object. I’m still struggling with this prototype lark, and would need to try lots more examples to get the hang of it. Stefan reopned this discussion recently on this list.

  3. Object literals and array literals Apparently a convenient notation for “creating new objects and arrays” and the inspiration for the JSON format.

That’s a very short list!

He mentions adding the constant pi to his Simplified JavaScript language, along with demonstrating a better reserved word policy (what this is, is not clear from here) and showing reserved words are not required, and added block scope. These are clearly not the beautiful parts of JavaScript, rather ones he would like.

He then rants a bit about feature-driven product design and microwave ovens having too many features, ending by saying “It would be nice if products and programming languages were designed to have only good parts.”

Appendix A: Awful Parts

Chris O’Dell, 28 January 2013

This appendix lists the awful part of JavaScript that are difficult to avoid along with some tactics to make things easier.

Global Variables

JavaScript doesn’t have a linker, so all compilation units are loaded into a common global object. This makes it harder to run independent subprograms together. Also, any variables used without defining them as implied as global.

Scope

The syntax looks like C, in that it has blocks, but it lacks block scoping - the variable is visible anywhere within the function containing the block.

A suggested way of handling this is to go against common convention and define all of your variables at the top of the function, instead of just before you need them.

Semicolon Insertion

JavaScript attempts to be helpful and will happily insert semicolons in an attempt to fix your “faulty” code. Unfortunately this can lead to some unexpected behaviour. The best way to avoid this is to place the braces at the end of the previous line thereby explicitly denoting that the statement isn’t quite finished and doesn’t need a magic semicolon.

Reserved Words

There exists as lit of reserved words, as is usual in most programming languages, but if you wish to use them as variable names then they will need to be wrapped in quotes and combined with square brackets when used in arrays.

Unicode

When JavaScript was defined Unicode was only expected to have no more than 65,536 characters. It is now more than 1 million. The remaining characters can be represented as a pair of characters which JavaScript will treat as two chars

typeof

As you would expect, this operator returns a string representation identifying the type. What you wouldn’t expect is some of it’s strange behaviour: typeof null returns ‘object’ and different implementations can also vary between themselves with some reporting a regex as an object and others as a function.

parseInt

Converts a string to an int. Except, it stops if it reaches a non-digit, which it doesn’t tell you about while it happily hands you the number part.

Also, numbers starting with 0 are assumed to be in base 8, at which time 8 and 9 are no longer digits so both parseInt('08') and parseInt('09') return 0. To get around this you can pass in an extra ‘radix’ parameter to specify the base which is a recommended practice.

+

This can add, if numbers, or concatenate if any of the variables are strings. Make sure all operands are numbers if you intend to add.

Floating Point

JavaScript adopted the IEEE 754 standard for binary floating point numbers, which can give unexpected results when dealing with decimals such as adding 0.1 + 0.2 is not equal to 0.3. The author suggests avoiding this whole problem by scaling the values up so there are no decimals before calculations and scaling back down afterwards.

NaN

Stands for ‘Not a Number’, which curiously has a typeof ‘number’, but it is not equal to itself. Any arithmetic operation involving a NaN always produces NaN as a result. JavaScript provides an isNaN function for testing values, although the author suggests using the isFinite method because it rejects the special cases of NaN and Infinity. Unfortunately it also tries to convert the value to a number and he suggests a little helper method.

Phony Arrays

Arrays aren’t real arrays, but they act very much the same, except considerably slower. The author goes on to detail how the methods for determining if an object is an array are faulty and generally give incorrect results depending on how the array was instantiated. Another helper method is provided.

Falsy Values

6 falsy values are listed along with a code sample demonstrating that they are not interchangeable. The double equals operator (==) performs type conversion and suggests the more reliable triple equals operator (===).

To top it off he states that undefined and NaN are not constants but global variables and can be overridden – this leads to madness, don’t do it.

hasOwnProperty

This is not an operator, but a function and as such can be overridden - beware.

Objects

Due to the prototype chain, objects are are never truly empty. An example is included where a piece of text is broken down and the number of repeating words is counted by looping through them and increasing the current count in an array. This piece of text include the word ‘Constructor’. When the code reaches count[Constructor] +=1 the array pulls out the parent object’s Constructor method instead of creating a new item labelled ‘Constructor’. The +=1 converts the constructor reference into a string and plonks a 1 onto the end of it. The author suggests checking for numbers explicitly.

Thoughts

This is the kind of awful stuff that is touted about JavaScript and exactly the kind of stuff that has made me run away from using it in earnest. There’s so much to trip up on and no way to know that you’ve fallen for one of these crackers until it explodes unexpectedly.

The suggested ‘helper’ functions do little to make me feel any better about it – do I need to write a few hundred lines of ‘helpful’ stuff just to make JavaScript sane before I can even get down to my task? I’m sure there’s libraries out there for this, but I don’t know any of them and would’t know what to search for to find it. It makes me wonder if NodeJS suffers these problems too, and if so, how are people writing robust systems with it?

Appendix B: Bad Parts

Ed Sykes, 4 February 2013

Quality operators

It seems that JavaScript has evil operators (with pointy beards presumably). These come in the form that we’re used to from other languages: == and != . These have an inconsistent set of rules that Crockford advises we avoid. I can see these operators being a source of errors for those moving over to JavaScript. Instead he advises that we use === and !=== which check for the same type and then the same value.

With statement

This statement is peculiar. As far as I can tell it allows you to speculatively try to access properties of an object, defaulting to global variables if those properties are not available. This looks particularly tricky and I’ll be avoiding this one. Crockford mentions that lexical parsing of the language would be easier without this feature.

Eval statement

Apparently this is JavaScript’s single most misused feature. Obviously Crockford has more experience than I do but I’ve never seen eval used in blog posts, stackoverflow or jsfiddles. Equivalent to the eval are setTimeout / setInterval with a string, Function constructor. Like with this also makes the language slower.

Continue statement

Douglas states that code is always better when you refactor this statement away. I’m not sure that I agree with this, it’s quite a black and white statement.

Switch fall through

An amusing tale is told, where a request is made to improve jostling to spot switch statement fall throughs. Douglas refuses the request, only to be informed of that there is a bug in his code ultimately caused by a switch fall through. Now he avoids fall throughs and advises us to do the same.

Blockless statements

A blockless statement is an if or a for that does not use curly braces. With this form of a statement it’s easy to make a mistake that results in a bug. I agree on this and would expect this advice to apply to all C family languages

++ −−

An example of a buffer overflow bug in C is used to justify throwing out the increment and decrement operators. The example given is certainly unwieldy and hard to understand but I don’t think I would give up all uses of them.

Bitwise operators

The bitwise operators are shown. In JavaScript the numbers are double precision floating point this means they must be converted into integers to do the bitwise operations. JavaScript isn’t really designed for this type of work and the operators are very slow when compared to closer to the metal languages

Function statement vs function expression

The use of a function statement like function foo(){} is compared to a function expression like function (){}(). They both look similar and can lead to confusion.

Statements are subject to function hoisting. In JavaScript this is legal (and weird for my c family brain):

myFunc();

function myFunc(){}

What’s happening is the function statement where the function is declared is hoisted to the top of the scope and therefore can be bound to the call. I can see how this would make programs hard to read.

Typed wrappers

Boolean, number and string have wrapped types that can be created with the new keyword. Avoid them.

New

The use of new is dangerous because if you forget to use it with a constructor function the global object will be bound to the this object. Only constructor functions should be capitalised to give visual cue when new is forgotten.

Void

Avoid

Appendix Ca: JSLint

11 February 2013 – Chris O’Dell

Appendix C seemed pretty large for a single write up, so it’s been split into two and this is the first half (pages 1–14). Comments and discussion welcome and encouraged :)

This section is all about JSLint - a tool Crockford created to check your javascript for any obvious pitfalls. It checks for syntax errors and structural problems; it was designed to be stricter that the ECMAScript 3 definition. It doesn’t check whether your program is correct, but less likely to stumble on the javascript pitfalls.

JSLint can be found at www.jslint.com.

For the remainder of the appendix Crockford lists some areas that JSLint looks for and some configuration settings if you wish to amend it’s sensitivity to these things.

Undefined Variables and Functions

As has been covered many times, javascript has a reliance on global variables and without explicit declarations it will assume that the variable should be global (e.g. misspellings).

Therefore JSLint will insist on all variables being explicitly declared and before their first use. Any expected global variables can be defined as exceptions to JSLint in following way:

/*global getElementByAttribute, breakCycles */

Members

At the end of the report JSLint will list all members that it encountered, any that are encountered only once are in italics and so this helps spot misspellings. You can add the Members comment to your script file and JSLint will check for misspellings automatically.

Options

These can be provided as a specification in the source of your script as name/value pairs like so:

/*jslint nomen:true, evil:false */

The options available are then listed.

Semicolon

JSLint expects every statement to be followed by a ; except for for, function, if, switch, try and while.

Line Breaking

JSLint only expect line breaks after certain characters, which are listed. Specifically, it does not expect line breaks after:

)  ]  ++  --

There is an option to turn off this check.

Comma

JSLint expects commas to be used as a separator, not as an operator (except in for statements)

Required Blocks

To prevent potential confusion and bugs, JSLint expects for and if statements to be blocks enclosed in braces ({ }).

Forbidden Blocks

As the reserve to the above, JSLint denies any blocks defined outside of function, if, switch, for, do & try. This is because Javascript does not have block scoping and the inclusion of the braces may confuse a programmer expecting otherwise.

Expression Statements

An expression statement is expected to be an assignment, a function/method call or delete. All other expression statements are considered errors.

For…in Statement

JSLint expects the body of these statements to be wrapped in an if statement to prevent looping through members inherited from the prototype chain.

Switch Statement

As javascript allows fall-through JSLint tries to prevent any unexpected behaviour by expecting the last statement of each case to be followed by either break, return or throw

var Statement

JSLint expects:

A var will be declared only once, and before it is used
A function will be declared before it is used
Parameters will not also be declared as vars

JSLint does not expect:

The arguments array to be declared as a var
That a variable will be declared in a block (as there is no block scoping)

with Statement

JSLint does not expect to see a with statement

= (equals)

JSLint does not expect to see a single equals in the condition part of a while or if statement - it is most likely a typo and should have been double equals.

== and !=

Due to the type coercion taking place with the above operators, the === and !== are always preferred by JSLint

Appendix Cb: JSLint

3 March 2013 – Ed Sykes

Labels

JSLint limits the use of labels. This is a feature that I didn’t see mentioned elsewhere in the book; at least I didn’t notice it. Labels allow control over which containing statement that a continue or break apply to. JSLint limits the use of labels to switch, while, do, for; the statements that continue and break apply to.

Unreadable code

JSLint checks for unreachable code. Seems sensible :)

Confusing pluses and minuses

Jslint checks how the plus and minus operators are being used. It was quite hard to follow what JSLint is trying to mitigate here but I think it’s this statement: myvalue++ + 5. I created a jsfiddle here to show how this gives the wrong value: http://jsfiddle.net/HjC29/

++ and −−

Apparently these two operators have been known to contribute to bad code and excessive trickiness. I’ve seen them used all over the place and in 15 years i’ve never seen this. I think it’s a bit too opinionated to rule out these operators. Luckily you can turn this option off.

Bitwise operators

The bitwise operators in javascript are slow. Don’t use them. That’s also the message from elsewhere in the book. JSlint prevents their use. I wonder if this changes at all when running javascript under nodejs?

eval is evil

Don’t use evil unless you’re an expert. JSLint prevents you using eval.

void

void is different in javascript. It’s not a type but a prefix operator that returns ‘undefined’. Apparently it is confusing and and not very useful so JSLint detects and prevents it. Here’s a fiddle with the use of void: http://jsfiddle.net/tqCbE/

Regular Expression

JSLint seems to force you to use regex in a particular style. Either as an assignment or on it’s own, not embedded within another string. This is due to its overloading of / for regex. This rule seems to be about trying to detect when you may have intended to use a regex, but you have in fact created a normal string. Have a look at this fiddle for more details: http://jsfiddle.net/pNDR8/

Appendix D: Syntax Diagrams

To not be reviewed.

Appendix E: JSON ()

Frances Bountempo, 25 February 2013