Perhaps the most interesting change that we can make is a rather subtle one, but it’s eschewing normal function declarations for creating anonymous functions and assigning them to a variable.
// Don't do this:
function getData() { }
// Do this instead:
var getData = function() { };
There are a number of good habits that are instilled when you use this particular technique.
- Makes it easier to understand “functions as an object”. I’ve found that when you show new developers a function being assigned to a variable it suddenly becomes much more obvious that a function is actually an object and can be manipulated as such (and that a function can be passed as an argument to another function). Thus students are advanced along the path towards a better understanding of functional programming.
- It enforces good semicolon habits. Traditional function declaration is the only situation in which semicolons aren’t needed (save for conditional statements and loops, naturally) and it makes it much more obvious when they’re required all the time.
- Doesn’t have much of the baggage traditionally associated with functions and scope.