0

I'm currently trying to print out the values of an array in JavaScript and I keep receiving 'undefined' output in the Chrome developer console where I'm running the following code:

function printArray(){
  var arr = [];
  for (var i = 0; i < arr.length; i++){
    arr = arr[i];
  }
}
printArray(['hello','world',1,2,3]);

Will someone please point out to me what I am doing wrong here that is preventing me from seeing the following returned in the console?

['hello','world',1,2,3]

Additionally I've tried wrapping my call to the printArray function inside of a console.log(); statement.

console.log(printArray(['hello','world',1,2,3]));
3
  • 2
    you have to pass the array into the function Commented Feb 5, 2018 at 19:33
  • jsfiddle.net/no789fh2 Commented Feb 5, 2018 at 19:35
  • Thank you Gholamali. I see this now and it seems like quite the oversight now with six months of hindsight and practice behind me. Commented Jul 17, 2018 at 17:54

3 Answers 3

3

First, you have to pass the array as argument to the function. Second, inside the function you can use the console.log to print each item of the array.

function printArray(arr){
  for (var i = 0; i < arr.length; i++){
    console.log(arr[i]);
  }
}
printArray(['hello','world',1,2,3]);

You can also use console.log(['hello','world',1,2,3]) without the need of the printArray function

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

2 Comments

might be worth noting that you can console.log the entire array as it is
Thank you. It was part of an exercise in calling it within a function (using a for loop). Iterating over the array and printing out the values to be more specific.
1

This will print all the values in the array:

function printArray(arr){
  for (var i = 0; i < arr.length; i++){
    console.log(arr[i]);
  }
}

printArray(['hello','world',1,2,3]);

Comments

0

Any reason why you wouldn't just console log the whole array?

console.log(['hello','world',1,2,3]);

1 Comment

Please see my response above to xavvvier. Primary purpose here was to iterate through the array values using a for loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.