For Loop inside Function, Array Enumeration

19 views Asked by At

Having some difficulty with this code for my assignment.

I'm supposed to create two functions.

  1. the first function is called calledInLoop that will accept one parameter and log the parameter.

    calledInLoop = function (parameter) {
        console.log(parameter);
    }
    
  2. the second function is called loopThrough that will accept an array, loop through each, and invoke the calledInLoop function. The result should be each element of the array is console logged.

    loopThrough = function (array) {
        for (var i = 0; i < array.length; i++){
            calledInLoop(array[i]);
        };
    }
    
    myArray = ['dog', 'bird', 'cat', 'gopher'];
    

console.log(loopThrough(myArray)); returns each element on its own console.log line but then returns undefined. Why is this?

2

There are 2 answers

0
RamenChef On

The call to console.log in console.log(loopThrough(myArray)); is only printing out undefined. It does this because loopThrough does not return anything, so it defaults to undefined.

The elements in the array are printed by a call to calledInLoop in loopThrough, which in turn calls console.log.

2
Prajval M On

Your loopThrough function does not return any value when called. Hence it's return value is undefined.

loopThrough = function (array) { 
       for (var i = 0; i < array.length; i++) 
             calledInLoop(array[i])
       return 1
 } 

Now this will return you 1. Similarly you can return any other values.