In JavaScript, we can print an array using a couple of methods. The easiest way to print an array using JavaScript is to use the console.log() method.
The first example shows how to print an array using just the console.log() method.
var anArray = ["This","is","a","array","of","strings"];
console.log(anArray);
#Output:
['This', 'is', 'a', 'array', 'of', 'strings']
If we want to print each element and not have it in an array, we can use a for loop to go through each element in the array and print each one.
var anArray = ["This","is","a","array","of","strings"]
for( var i=0; i<anArray.length; i++ ){
console.log(anArray[i]);
};
#Output:
This
is
a
array
of
strings
And finally, if we want to print all the items in the array on one line as one long string, we can use the join() method to convert the array to a string and then print it.
var anArray = ["This","is","a","array","of","strings"];
console.log(anArray.join(" "));
#Output:
This is a array of strings
When working with arrays, it can be useful to be able to print the items of an array.
We can easily print the elements of an array in JavaScript using a number of different methods.
We can print an array by using the console.log() method. This will print the array of object to the console. Once again, here is our code to do this:
var anArray = ["This","is","a","array","of","strings"];
console.log(anArray);
#Output:
['This', 'is', 'a', 'array', 'of', 'strings']
Typically, we want to get only the elements of the array, and not the array. To print the items of an array to the console with JavaScript, we use a for loop to print the elements of an array.
Here is our code again to do this:
var anArray = ["This","is","a","array","of","strings"]
for( var i=0; i<anArray.length; i++ ){
console.log(anArray[i]);
};
#Output:
This
is
a
array
of
strings
Printing the First N Elements of an Array in JavaScript
In JavaScript, we can easily print the first n items in an array. To do so, we can use a for loop as shown in the second example of this article.
To print the first n items of an array, we just loop over those first n elements and print them out.
Below is an example that prints out the first 10 items of an array in JavaScript.
var numbersArray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
for( var i=0; i<10; i++ ){
console.log(numbersArray[i]);
};
#Output:
0
1
2
3
4
5
6
7
8
9
Hopefully this article has been useful for you to understand how to use javascript to print an array.