Useful Platitudes

Notes on programming by Daniel Mendel

Cool Stuff I Learned Doing Code Review

So a major staple of Hacker School is doing ( and getting ) lots and lots of code reviews. I think this is awesome, and I’ve been working on a lot of reviewing this week. The most rewarding thing about reviewing a language you are comfortable in is that you learn all kinds of things you might never come across when left to your own ingrained design patterns. This is a short round up of some neat things I learned about javascript this week.

Not just syntax!

1
2
function foo(){ return true };
var bar = function(){ return true };

I had always assumed that the only difference between these styles of defining a function was syntactic – however, that’s not true! There is actually a crucial difference at runtime.

1
2
3
4
foo();  // true
bar();  // ERROR! bar is not defined.
function foo(){ return true };
var bar = function(){ return true };

This is one of those things that now I know it, seems obvious. The essential difference is that javascript loads all of the function definitions in a chunk of code before it begins execution. When it encounters foo() it already has a reference to the function definition below. However, the bar function is actually anonymous until the line assigning it to bar is executed – because this is after the line that tries to run bar() the call fails.

– with Allie Jones

Do While

For some reason I have simply never really used javascript’s do {} while () loop. I use while(){} style loops all the time and somehow in the back of my mind must have foolishly assumed that they were all I’d ever need for a while ( pun! ). I was wrong, there are cases where this syntax is super useful, consider this essential difference between the two.

1
2
3
4
5
do{ var a = 1; }while( false );
while( false ){ var b = 1; };

a; // 1
b; // undefined

do always fires at least once. This makes it perfect for things like collision prevention without having to init a variable separately.

1
2
// assume uniqueRandoms === { ... };
do{ var a = Math.random() } while( uniqueRandoms.hasOwnProperty(a) )

– with Bill Abresch

Applied Math

Somehow I had never considered the pure simple genius of this strategy.

1
2
var arr = [ 20, 124, 240, 12, 10, 2 ];
Math.max.apply( Math, arr );  // 240

– with Greg Altman and Patrick Estabrook