Jeremy Wilson
Jeremy Wilson

Reputation: 29

Having difficulty printing all the values of a JavaScript array

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]));

Upvotes: 0

Views: 56

Answers (3)

frodo2975
frodo2975

Reputation: 11725

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

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

Upvotes: 0

Javier Gonzalez
Javier Gonzalez

Reputation: 1015

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

Upvotes: 3

darksmurf
darksmurf

Reputation: 3967

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]);

Upvotes: 1

Related Questions