How To Print Multiple Objects In Javascript

In this tutorial, we are going to learn how to print multiple objects in JavaScript. Whether you are debugging or developing an application, the ability to print objects is invaluable.

We will look into various methods to achieve this, such as using console.log() and JSON.stringify() functions in JavaScript.

Step 1: Using console.log()

The most common way to print objects in JavaScript is by using the console.log() method. This method accepts multiple arguments separated by a comma, which means you can pass multiple objects to it for printing. Here’s an example:

Output:

{ name: 'John', age: 30 } { name: 'Jane', age: 28 }

Step 2: Using JSON.stringify()

Another way to print objects is by using the JSON.stringify() method. This method converts a JavaScript object or value to a JSON string. You can use it with console.log() to display multiple objects nicely formatted on the console. Here’s an example:

Output:

{
    "name": "Alice",
    "age": 25
} {
"name": "Bob",
"age": 27
}

The second and third parameters in the JSON.stringify() method control the formatting:

  • Replacer (second parameter): A function that alters the behavior of stringification or an array of specific properties
  • Space (third parameter): A numeric value or string that controls the indenting of the resulting JSON string

In our example, we have set the replacer parameter to null and the space parameter to 2, which results in nicely formatted JSON objects.

Step 3: Using Template Literals

You can also print multiple objects using template literals. Template literals are string literals that allow embedded expressions. Here’s an example of using template literals with console.log():

Output:

{
"name": "Charlie",
"age": 31
}
{
"name": "Diana",
"age": 29
}

In the above code, we have used the template literal (backtick) syntax to print both objects separated by a newline character.

Full code:

Output:

{ name: 'John', age: 30 } { name: 'Jane', age: 28 }
{
"name": "Alice",
"age": 25
} {
"name": "Bob",
"age": 27
}
{
"name": "Charlie",
"age": 31
}
{
"name": "Diana",
"age": 29
}

Conclusion

In this tutorial, we have learned how to print multiple objects in JavaScript using different methods such as console.log(), JSON.stringify(), and template literals. These methods are helpful for debugging, visualizing, and formatting the output of your JavaScript code. Choose the appropriate method that suits your requirement and provides the desired output format.