refactored code to iterate through names array using a foreach loop in javascript