Posts

Showing posts with the label for-loop

For loops in JavaScript functions

For loops in JavaScript functions const animals = ["dog", "cat", "tree frog"]; function pluralize(array) { for (var i = 0; i <= array.length; i++) { array[i] += "s" return (array) } } console.log(pluralize(animals)); My goal is to create a function that adds the s to the end of words. However when I ran my code s was only added to the first word in the array. Why was the s not added to the other words in the array? Because you immediately return in your loop. Move the return out of the loop to the end of the function. – ASDFGerte Jul 1 at 9:13 return return Also you should iterate to i < array.length . Otherwise you will operate on array[array.length] , which is after the last element. – ASDFGerte Jul 1 at 9:20 ...