Fix variable scope

Prevents `lastKey` variable from polluting the global scope.