How to Print Array in JavaScript: Simple Methods Explained
To print an array in JavaScript, use
console.log(array) to display the whole array in the console. You can also print each element individually using a for loop or convert the array to a string with array.join().Syntax
Use console.log(array) to print the entire array at once. To print elements one by one, use a for loop like for(let i = 0; i < array.length; i++). The join() method converts the array into a string with elements separated by a specified character.
javascript
console.log(array); for(let i = 0; i < array.length; i++) { console.log(array[i]); } console.log(array.join(', '));
Example
This example shows how to print the whole array, each element separately, and the array as a string with commas.
javascript
const fruits = ['apple', 'banana', 'cherry']; // Print whole array console.log(fruits); // Print each element for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } // Print array as a string console.log(fruits.join(', '));
Output
[ 'apple', 'banana', 'cherry' ]
apple
banana
cherry
apple, banana, cherry
Common Pitfalls
One common mistake is trying to print an array directly inside a string without converting it, which results in object Object or unexpected output. Also, using console.log inside loops without understanding asynchronous behavior can confuse beginners.
javascript
// Wrong way: printing array inside string without conversion const numbers = [1, 2, 3]; console.log('Numbers: ' + numbers); // Works but implicit conversion // Better way: use join to control output console.log('Numbers: ' + numbers.join(', '));
Output
Numbers: 1,2,3
Numbers: 1, 2, 3
Quick Reference
- console.log(array): Prints the whole array.
- for loop: Prints each element individually.
- array.join(separator): Converts array to string with separator.
Key Takeaways
Use console.log(array) to print the entire array quickly.
Use a for loop to print each element on its own line.
Use array.join(', ') to print the array as a readable string.
Avoid printing arrays inside strings without conversion to prevent confusing output.