On JavaScript Enlightenment

Keeping with the theme of JavaScript books, I recently read JavaScript Enlightenment by Code Lindley. He writes:

It was my intention to write a book to give the reader an accurate JavaScript worldview through an examination of native JavaScript objects and supporting nuances: complex values, primitive values, scope, inheritance, the head object, etc.

Indeed, the book is all about objects. O’Reilly released the first edition in January 2013. It targets ECMAScript 3, which is becoming increasingly outdated. However, a lot of the book’s content touches on the fundamentals of the language. It’s still relevant, especially for beginners. Here’s my thoughts and learnings:

  • Mr. Lindley shows many examples with primitive constructors (String, Number and Boolean). This can be confusing, because these aren’t often seen in the wild. Using them can have unwanted effects:

    var myString = new String('hello');
    console.log(typeof myString); // "object"
    

    JavaScript uses the String primitive in the background to coerce strings to act like objects, which is why one can write myString.length.

  • Constructor functions are unique in that they return an object (unless otherwise specified.) JavaScript makes the object behind the scenes; this in a constructor is that object.

  • The book drills home the importance of the prototype chain. All the complex values inherit from Object. Mr. Lindley writes:

    The Object() constructor function in JavaScript is special, as its prototype property is the last stop in the prototype chain.

    Therefore, it’s bad form to alter Object’s prototype.

  • Using the Function() constructor doesn’t create a closure. Fun, impractical fact.

  • A function’s length property is the number of expected arguments.

  • This is a self-invoking function:

    !function sayHi(msg) {console.log(msg);}('Hi');
    
  • Regarding the “head,” or global object:

    Being explicit [e.g., window.alert() versus alert()] costs a little bit more with regards to performance…It’s faster if you rely on the scope chain alone.

  • Here’s a concise version of inheritance with constructors (page 101):

    var Person = function (){this.bar = 'bar'};
    Person.prototype.foo = 'foo';
    
    var Chef = function(){this.goo = 'goo'};
    Chef.prototype = new Person();
    var cody = new Chef();
    
    console.log(cody.foo); // logs 'foo'
    console.log(cody.goo); // logs 'goo'
    console.log(cody.bar); // logs 'bar'
    

    Setting Chef’s prototype to new Person() is what makes inheritance possible. ES6’s class and extends is syntactic sugar for this pattern.

  • The null type in JavaScript is meant for a placeholder on object values. Running typeof null results in object.

Overall, the book reinforces important facts about objects, prototypes and inheritance in JavaScript. The writing is easy to understand, and it’s a fast read. It’s a great starting point and knowledge refresh on the language.