Fixing bug where var declarations in for loops outlast the loops