/ #AngularJS #Javascript 

2 Things I learned by reading the AngularJS Source Code

I’m busy working on a curriculum for my favourite front end Javascript framework AngularJS.  To really understand it, I have been stepping through and reading the AngularJS Source.

This codebase is awesome! well written and well documented.  Over and above understanding AngularJS, this is what I have learned along the way.

1) Doing more things faster with for I have always just used for for the basic pro-forma like this:-

for (var j=0; j < myArray.length; j++) { 
//do stuff with j 

But the for loop can do so much more, check this out from the AngularJS source…


// iterate over the attributes 

for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, 

j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { 

Wow! here, they are initialising all sorts of variables that will be used in the loop, not just the iterator variable ‘j’

Also, note that they are ‘caching’ the length of the array in the variable ‘jj’.  Turns out that this is a great optimisation technique and makes the loop go faster because you don’t need to re-evaluate the length property on each loop.

for more details on optimising loops, check out these links

2) Assignment returns a value.. Use it

Look at this..

if (directiveValue = directive.scope) { 

This looks like a mistake at first.. usually you use ‘==’ in your if statements however this is definitely on purpose.  The assignment returns a value.  In this case, it returns the value of directive.scope to the ‘if’ statement.  ’if’ will evaluate any object to true (unless it is undefined) so this statement has both sets the directiveValue to the directive.scope object and checks if the directive.scope is defined.. elegant!

There are some more good examples of this here..



Michael Dausmann

Full stack developer. Agile, Data science and Machine Learning. Love learning, speaking and dad jokes. Tweets are my own.