➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
Printing Array In JavaScript | We will learn how to print object arrays in JavaScript in this tutorial.
What are object arrays and object arrays? When storing several values in one variable, an array of objects holds a fixed-size sequential collection of identical elements. You have two choices in a browser environment: write it to the DOM or use the console.log() function. This post will show examples of the two ideal methods to print out your array.
Printing Array In JavaScript Using console.log()
The simplest method is using the console.log() function to print out an array. You can print out each element one at a time by iterating through each one.
const array = [1, 2, 3, 4, 5];
console.log(array);
Output:-
[ 1, 2, 3, 4, 5 ]
const numbers = [10.5, 20.1, 30.5, 42.3, 55.9];
console.log(numbers);
Output:-
[ 10.5, 20.1, 30.5, 42.3, 55.9 ]
const chars = ['a', 'A', 'c', 'D', 'z'];
console.log(chars);
Output:-
[ ‘a’, ‘A’, ‘c’, ‘D’, ‘z’ ]
const langs = ["Java", "JavaScript", "HTML", "Python", "C++"];
console.log(langs);
Output:-
[ ‘Java’, ‘JavaScript’, ‘HTML’, ‘Python’, ‘C++’ ]
const objects = ["Java", 1, 'a', 20.5, true];
console.log(objects);
Output:-
[ ‘Java’, 1, ‘a’, 20.5, true ]
Print Each Element In Array JavaScript
To print each element of the given array, we can iterate the array elements and use the console.log() function to display the element.
const array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
Output:-
1
2
3
4
5
The same thing can be done using multiple ways. One of the most efficient ways is to use the map() method.
const array = [1, 2, 3, 4, 5];
array.map((element) => {
console.log(element);
});
The forEach() method also can be used in a very similar way:-
const array = [1, 2, 3, 4, 5];
array.forEach(element => {
console.log(element);
});
Writing the Array to the DOM
Before writing it to the DOM, you must first convert your array to a string. Thankfully, we can accomplish this using JSON.stringify() function. Our array can be converted to a string using JSON.stringify() function, and we can then post the string to the DOM.
const array = [1, 2, 3, 4, 5];
const string = JSON.stringify(array);
document.getElementById("output").innerHTML = string;
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!