HTML DOM console.table() Method


The HTML DOM console.table() method is used to display data in a well organized tabular format. This method can be used to visualize complex arrays or objects. The table is organized in such a way that each element in the array will be a row in the table. It takes two parameters tabledata(compulsory) and tablecolumns(optional).

Syntax

Following is the syntax for the console.table() method −

console.table( tabledata, tablecolumns );

Here −

  • Tabledata is a compulsory parameter value. It represents the data to be used in filling the table. It can be of type object or an array.

  • Tablecolumns is an optional parameter value.It is an array parameter that specifies which of the columns should be displayed in the table.

Example

Let us look at an example for the HTML DOM console.table() method −

<!DOCTYPE html>
<html>
<body>
<h1>console.table() Method</h1>
<p>Click on the below button to create a console table</p>
<button type="button" onclick="createTable()">TABLE</button>
<script>
   function createTable(){
      var fruit1 = { Name : "Mango", price : "100", color: "Yellow" }
      var fruit2 = { Name : "Guava", price : "50", color:"Green" }
      var fruit3 = { Name : "Strawberry", price : "150", color:"Red" }
      console.table([fruit1, fruit2, fruit3], ["Name","price"]);
   }
</script>
<p>View the table in the console tab</p>
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the TABLE button and viewing it in the console tab −

In the above example −

We have first created a button table that will execute createTable() function upon being clicked by the user.

<button type="button" onclick="createTable()">TABLE</button>

The createTable() method has three arrays of objects created inside it. The arrays of objects are named fruit1, fruit2 and fruit3 respectively. Then the name of the array of objects are passed as the first parameter(tableData) to the table() method of console.

In the second optional parameter we pass the name of the columns as an array, we want to include in the table. Since we have specified “Name” and “price” column; these columns will be seen in the table and there will be no “color” column −

function createTable(){
   var fruit1 = { Name : "Mango", price : "100", color: "Yellow" }
   var fruit2 = { Name : "Guava", price : "50", color:"Green" }
   var fruit3 = { Name : "Strawberry", price : "150", color:"Red" }
   console.table([fruit1, fruit2, fruit3], ["Name","price"]);
}

Updated on: 08-Aug-2019

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements