Whether you’re hunting for a bug or writing code, you likely use Javascript’s ‘console.log()’. It works but console
has 19 other methods to assist your development and debugging.
Most notably is console.table()
when working with objects and arrays, which provides a prettier format for these data types.
console.table() - for arrays, objects, and mixed data types
Output an Array and Array of Arrays
‘console.table’ provides the index on the left and indexed values or just ‘value’ across the top for array or array of arrays.
A 1d array with .table() vs .log()
:
const namesStartingWithA = ["Alec", "Alexis", "Anastasia", "Andre", "Andrea", "Andrew", "Andrew"]
> console.table(namesStartingWithA)
>
Index Value
0 "Alec"
1 "Alexis"
2 "Anastasia"
3 "Andre"
4 "Andrea"
5 "Andrew"
6 "Andrew"
> console.log(namesStartingWithA) // same data as above looks like this
> (7) ["Alec", "Alexis", "Anastasia", "Andre", "Andrea", "Andrew", "Andrew"]
A 2d array with .table() vs .log()
:
const namesStartingWithA = [ ["Alec", "Alexis",], ["Anastasia", "Andre", "Andrea"], "Andrew", "Andrew"]
> console.table(namesStartingWithA)
>
Index 0 1 2 Value
0 "Alec" "Alexis"
1 "Anastasia" "Andre" "Andrea"
2 "Andrew"
3 "Andrew"
> console.log(namesStartingWithA)
>(4) [Array(2), Array(3), "Andrew", "Andrew"]
Output of Objects and Arrays of Objects
When outputting an array of objects, the keys become headers. If the data has many values or many keys, avoid using ‘console.table()’.
> console.table(namesStartingWithAWithId)
>
Index Name ID
0 "Alec" 8
1 "Alexis" 69
2 "Anastasia" 815
3 "Andre" 68
4 "Andrea" 062
5 "Andrew" 97
6 "Andrew" 772
> console.log(namesStartingWithAWithId)
> (86) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Show Selected Columns Only
It is possible to select just the column(s) you want to see.
For example: ‘console.table(data, [‘columnName’])’ You do need the brackets and single quote. [‘ ‘]
.
> console.table(namesStartingWithAWithId, [“id”])
>
Index ID
0 8
1 69
2 815
3 68
4 062
5 97
6 772
Not Recommended On Complex or Long Data
Because ‘console.table()’ is highly visual, long arrays or complex objects are likely harder to understand in this table format unless you specify the column(s).
Other Useful console.table Tidbits
- In Firefox,
console.table()
displays only 1000 rows. - Click a header column name and the browser sorts the table based on the column data (ASC and DSC).
Top comments (0)