0

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

got it. what would i end the loopThrough function with?
It's okay if your function does not return any value. You can return true or 0 ( most common practice ) if you want just to show that your function returned something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.