Interview Q&A / JavaScript

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How would you mask all but the last four digits of a card number in JavaScript?

SHORT ANSWER

Take the last four characters with slice(-4) and pad the front back to the original length with padStart(length, '*'). padStart and padEnd fill a string to a target length from the left or right.

Explain it simply

Payment apps show cards like "**** 5678" so nobody sees the full number. You only need the last four digits and a way to fill the rest.

slice(-4) takes the last four characters. padStart(targetLength, fillString) then adds the fill character on the left until the string reaches the target length. Using the original length as the target restores the original width, with stars where the hidden digits were.

padEnd does the same on the right, useful for aligning text columns in plain output.

Example

js
function maskCard(number) {
  const digits = String(number);
  return digits.slice(-4).padStart(digits.length, "*");
}

console.log(maskCard("1234567812345678"));     // Output: ************5678
console.log(maskCard("1234567812345678").length); // Output: 16
console.log("7".padStart(3, "0"));             // Output: 007
console.log("Name".padEnd(8, ".") + "Fee");    // Output: Name....Fee

What to say in the interview

"I slice the last four characters and use padStart to restore the original length with asterisks. I take the input as a string, because a long card number as a Number can lose precision. Real masking should also happen on the server."

Common mistakes

  • Storing a card number in a Number type. Long values lose digits.
  • Masking only in the UI while the full value is still sent to the page.

#javascript#strings

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.