Bugfix: angular.js:8619 TypeError: Cannot read property ‘1’ of null
 at Function.annotate [as $$annotate]

TL; DR: Don’t use arrow functions as the constructor into angular.factory (or really anywhere)

While working with Angular 1 today, I made a lot of changes without committing (yeah… I know 🙄) and suddenly ran into this error:

angular.js:8619 TypeError: Cannot read property ‘1’ of null
at Function.annotate [as $$annotate]

The call stack seemed to be unhelpful, just a route through lots of Angular modules:

Possibilities

Most blogs/ Stack Overflow suggest that the error probably originates from a syntax error in one of your directives (i.e. you mispelled your controller in a ng-controller=”foo” tag).

However, that wasn’t the case for mine.

I ended up finding this GitHub issue from last year, which opened me up to the possibility that there might be some ES6 issues with parts of the Angular 1 API.

Here is the code causing the problem (notice the arrow function as the constructor in the .factory method invocation on line 4):

This is the right way (replaced arrow function with traditional function expression):

Explanation

I think the bug originated from the fact that ES6 arrow functions don’t create their own this context, as most functions do, but instead inherit their context from their enclosing scope.

This is a feature of arrow functions, which were meant to be used to create short anonymous functions with a minimal syntax. Arrow functions aren’t supposed to be used as constructors, because they don’t have their own context.

Read more about it here (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

So the meta-lesson is don’t use ES6 arrow functions as constructors, and all bugs have causes.