JavaScript: Loop Optimization