Move function to outer scope

Since the 'if' doesn't introduce a new scope, it's best if the function is at the top level to stop any misunderstandings. This also stops `grunt jshint` complaining too.