Lining Up Text in Columns

Template literals are good for sentences. For tables, where values must line up in columns, you need strings of a fixed width. Three methods help with that:

console.log("Alice".padEnd(8) + "|");
console.log("7".padStart(3, "0"));
console.log("=".repeat(12));

Output:

Alice   |
007
============
  • padEnd(8) adds spaces at the end until the string is 8 characters long. The text stays on the left. This suits names and labels.
  • padStart(3) adds the spaces at the front instead, so the text moves to the right. Numbers usually go on the right, so their last digits line up. An optional second argument sets the padding character, which is how "7" became 007.
  • repeat(12) repeats a string 12 times. It is an easy way to draw a divider line.

With fixed widths, rows line up into columns:

console.log("Coffee".padEnd(8) + "3".padStart(3));
console.log("Tea".padEnd(8) + "12".padStart(3));

Output:

Coffee    3
Tea      12

Each name takes exactly 8 characters and each number exactly 3, so the numbers line up on the right.

In a real program the quantity is usually a number, not a string. Padding methods belong to strings, so a number does not have them:

const qty = 3;
console.log(qty.padStart(3));

Output:

/box/index.js:2
console.log(qty.padStart(3));
                ^

TypeError: qty.padStart is not a function
    at Object.<anonymous> (/box/index.js:2:17)

Convert the number with String() first, then pad it:

const qty = 3;
console.log(String(qty).padStart(3) + "|");

Output:

  3|

Money needs one more tool. toFixed(2) turns a number into a string with exactly two digits after the decimal point:

const price = 1.2;
console.log(price * 4);
console.log((price * 4).toFixed(2));

Output:

4.8
4.80

So the rule is simple. Do the math with numbers, then turn the result into a string and format it.

In the exercise, print a three-line receipt: a divider, the item name and quantity in aligned columns, and the total with two decimals.