Formatting text to add new lines in JavaScript and form like a table?

To format text with new lines in JavaScript and create table-like output, use the map() method combined with join('
')
. The '
'
character creates line breaks in console output.

Syntax

array.map(element => `formatted string`).join('
')

Example: Creating a Table-like Format

let studentDetails = [
    [101, 'John', 'JavaScript'],
    [102, 'Bob', 'MySQL'],
    [103, 'Alice', 'Python']
];

// Create header
let tableHeader = '||Id||Name||Subject||
'; // Format data rows let tableRows = studentDetails.map(student => `|${student.join('|')}|` ).join('
'); // Combine header and rows let formattedTable = tableHeader + tableRows; console.log(formattedTable);
||Id||Name||Subject||
|101|John|JavaScript|
|102|Bob|MySQL|
|103|Alice|Python|

Step-by-Step Breakdown

Here's how the formatting works:

let data = [['A', 'B'], ['C', 'D']];

// Step 1: Map each array to a formatted string
let formatted = data.map(row => `|${row.join('|')}|`);
console.log('Formatted array:', formatted);

// Step 2: Join with newlines
let result = formatted.join('
'); console.log('Final result:
' + result);
Formatted array: [ '|A|B|', '|C|D|' ]
Final result:
|A|B|
|C|D|

Enhanced Table with Separators

let employees = [
    ['ID', 'Name', 'Department'],
    ['001', 'Sarah', 'Engineering'],
    ['002', 'Mike', 'Marketing']
];

let separator = '+-----+----------+-------------+';
let formattedTable = employees.map((row, index) => {
    let formattedRow = `| ${row[0].padEnd(3)} | ${row[1].padEnd(8)} | ${row[2].padEnd(11)} |`;
    return index === 0 ? separator + '
' + formattedRow + '
' + separator : formattedRow; }).join('
'); console.log(formattedTable);
+-----+----------+-------------+
| ID  | Name     | Department  |
+-----+----------+-------------+
| 001 | Sarah    | Engineering |
| 002 | Mike     | Marketing   |

Common Use Cases

  • Data Export: Format arrays for CSV-like output
  • Console Tables: Display structured data in readable format
  • Report Generation: Create formatted text reports
  • Log Files: Structure log entries with consistent formatting

Conclusion

Use map() with join('
')
to format arrays into table-like text structures. This approach provides flexible control over data presentation in console applications.

Updated on: 2026-03-15T23:18:59+05:30

415 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements