Write JavaScript like it’s typed

Over my career I’ve written in a number of different programming languages, most of them dynamic. It’s been about 10 years since I last wrote a project from start to finish in a typed language, C++, but recently I’ve been working with Go. It’s safe to say I had become blissfully ignorant of the benefits and challenges of a typed language and in working with Go I found myself really enjoying the explicit declaration of types with regards to stability and code legibility.

In many JavaScript projects you’ll see something like this:

function dataFiller() {
  var myObject = {};
  // 5 lines later
  myObject.Foo = 'bar';
  // 10 lines later
  myObject.Baz = 'bax';
  // 5 lines later
  return myObject;
}

This essentially means that you must read through an entire functions execution, and sometimes an entire modules execution to see what the structure of that object will become.

Now lets compare that to Go:

type myObject struct{
  Foo string
  Baz string
}

func dataFiller() *myObject {
  var data = &myObject{}
  // 5 lines later
  data.Foo = "bar"
  // 10 lines later
  data.Baz = "bax"
  // 5 lines later
  return data
}

Here you don’t even have to read further than the function declaration to know what the function will return and then you simply have to reference that type in the file to know ahead of time what it’s structure will be.

Throughout my time as a developer I’ve noticed that it’s quite rare that you cannot predict with 100% certainty what the data structure of your variables will be but, in dynamic languages, we don’t ever seem to outline that structure for people reading and writing the code. So this got me thinking about how this workflow can be adopted in JavaScript to give us the benefits of types using the native language constructs without having to use a compile target like Typescript. In practice it turns out to be quite simple:

// Method to convert defined object literal 'type' 
// into a 'locked down' data store.
function createObject(obj) {
  var stub = Object.create(null);
  var keys = Object.keys(obj).forEach(function(key) {    
    Object.defineProperty(stub, key, {
      configurable: true,
      enumerable: true,
      writable: true,
      value: obj[key]
    });
  });
  Object.seal(stub);
  return stub;
}

// Your 'type' which will be used to create
// usable data store instances. 
var myObject = {
  Foo: '',
  Baz: ''
};

// Fills the object with data.
// @method dataFiller
// @return {myObject} 
function dataFiller() {
  var data = createObject(myObject);
  // Set values like normal.
  data.Foo = 'bar';
  data.Baz = 'bax';
  return data;
}

var fullData = dataFiller();
fullData.Foo = "can Update"; // Updated
fullData.Qux = "Can't add new properties"; // Not added

Following this pattern will allow you to write JavaScript with predefined data type which helps tremendously in readability with minimal amount of additional work. This is just a basic example to show how the typed structure could be applied to JavaScript, the createObject() method could be expanded on to add getters and setters which could enforce the property types and you could even expand this idea to use Go like interfaces following a similar structure. I feel the trivial trade-off in additional lines of code is well worth the structure which is now being enforced. What do you think? Have you written a large JavaScript application before where predefined data structures helped? Let me know in the comments below or on twitter @fromanegg. Thanks for reading!

a/A W7D1 - Intro to Backbone.js

We spent one day on AJAX last Friday as a pre-intro into Backbone.js. Backbone is a library that helps making AJAX requests easier or at least that’s what I think it does.

Our assignment focused on making a Pokedex (I don’t know what that is either. Well, now I know it’s Pokemon related.). This pokedex is a database of pokemon and their attributes. This intro started us off creating Backbone models and collections which we used to populate html elements on our single-page website.

Circular References: The Positives

My last post talked about circular references, mainly focusing on the negatives. But there are also positives. They can simplify navigation through objects which helps make code simpler. For example, for navigation through a document tree in JS. If a function is passed a child, a circular reference to its parent makes getting the name trivial:

var doc = {};
doc.name = 'Test1',
doc.children = [
    {
        name: 'child1',
        parent: doc
    },
    {
        name: 'child2',
        parent: doc
    }
];

var someFunction = function(ele) {
    console.log(ele.parent.name);
};

someFunction(doc.children[0]);// 'Test1'
someFunction(doc.children[1]);// 'Test1'

Without having a parent reference the entire document would need to be searched and the child and parent would need to be tracked.

This tactic is best only tried with self similar objects as knowledge of the parent is needed by the child. The DOM uses a similar system to the above. The parent is unknown, but it needs to be known to do a DOM operation. So every element places a parentNode circular reference to itself in its children.

Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2015/circularReferencePositives.js

Applying NASA coding standards to JavaScript

Jet Propulsion Laboratory – scientific institution making a lot of research and development for NASA. JPL have been developing software for most of unmanned missions in the field of deep space and other planets exploaration. Their portfolio includes such famous missons as Curiosity Mars rover and Voyager probe which left solar system after 25 years of flight and still providing scientific information. High level of autmatization and long duration of missions led to superior demands to software quality. As a result of JPL amazing experience a set of code guidelines was developed and published recently. Since demands to web-driven software constantly increase and more critical tasks are entrusted to JavaScript, lets apply NASA coding guidelines to JavaScript / HTML applications for higher performance, reliability and the better world… “

The Power of Ten: 10 Rules for Writing Safety-Critical Code