This line (`var type = ...`) should be at the top of this function instead of in the loop.