js loop made more efficient