0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Console Table in JavaScript: Syntax and Examples

Use console.table() in JavaScript to display arrays or objects as a formatted table in the browser console. Pass your data as an argument, and the console will show it in rows and columns for easy reading.
📐

Syntax

The basic syntax of console.table() is simple:

  • console.table(data): Displays the data as a table in the console.
  • data can be an array, an object, or an array of objects.

This method helps visualize structured data clearly.

javascript
console.table(data);
💻

Example

This example shows how to use console.table() with an array of objects representing people:

javascript
const people = [
  { name: 'Alice', age: 25, city: 'New York' },
  { name: 'Bob', age: 30, city: 'London' },
  { name: 'Carol', age: 22, city: 'Paris' }
];

console.table(people);
Output
┌─────────┬─────────┬─────┬───────────┐ │ (index) │ name │ age │ city │ ├─────────┼─────────┼─────┼───────────┤ │ 0 │ 'Alice' │ 25 │ 'New York'│ │ 1 │ 'Bob' │ 30 │ 'London' │ │ 2 │ 'Carol' │ 22 │ 'Paris' │ └─────────┴─────────┴─────┴───────────┘
⚠️

Common Pitfalls

Some common mistakes when using console.table() include:

  • Passing data types that are not arrays or objects, which will not display as a table.
  • Expecting nested objects to display fully; nested objects show as [object Object].
  • Trying to use console.table() in environments that do not support it (like some older browsers).

Always check your data structure before using console.table().

javascript
/* Wrong: Passing a string */
console.table('hello'); // Shows each character as a row

/* Right: Pass an array or object */
console.table(['h', 'e', 'l', 'l', 'o']);
Output
/* Wrong output: */ // ┌─────────┬─────────┐ // │ (index) │ Values │ // ├─────────┼─────────┤ // │ 0 │ 'h' │ // │ 1 │ 'e' │ // │ 2 │ 'l' │ // │ 3 │ 'l' │ // │ 4 │ 'o' │ // └─────────┴─────────┘ /* Right output: */ // Same as above, but intentional array usage
📊

Quick Reference

UsageDescription
console.table(array)Displays array elements as table rows
console.table(object)Displays object properties as table rows
console.table(arrayOfObjects)Displays each object as a row with columns for keys
console.table(data, columns)Displays only specified columns from data

Key Takeaways

Use console.table() to display arrays or objects in a clear table format in the console.
Pass arrays, objects, or arrays of objects as the argument to console.table().
Nested objects may not display fully; consider flattening data if needed.
Avoid passing unsupported data types like strings directly to console.table().
console.table() is supported in most modern browsers' developer consoles.