use javascript idiom to create output string
improved efficiency of the algorithm and fix a comment