Spot the bug - #99: Text Preview Box

This title-case formatter mangles every other word somehow.

function toTitleCase(sentence) {
  const words = sentence.split(' ');
  const result = [];

  for (let i = 0; i < words.length; i++) {
    const word = words[i];
    const firstLetter = word.charAt(0).toUpperCase();
    const rest = word.slice(1).toLowerCase();
    result.push(firstLetter + rest);
  }

  return result.join(' ');
}

const headlines = [
  'the quick brown fox',
  'ATTACK OF THE KILLER TOMATOES',
  'a tale of two cities'
];

headlines.forEach(h => {
  console.log(toTitleCase(h));
});

const nameTag = document.getElementById('preview');
nameTag.textContent = toTitleCase('welcome new employee');

Reply with what is broken and how you would fix it.

Spot the Bug answer: There is no actual bug in the toTitleCase logic itself; it correctly title-cases every word, so the claim that it mangles every other word is false (the real issue is a false premise, but if forced to find something, it does not handle multiple spaces or empty strings between words, producing lowercase-only fixes for empty tokens instead of mangling alternating words).

The fix:

const firstLetter = word.charAt(0).toUpperCase(); const rest = word.slice(1).toLowerCase(); if (word.length === 0) { result.push(''); continue; } result.push(firstLetter + rest);

Why:
The function processes every word identically using charAt(0) and slice(1), so there is no mechanism that would cause it to skip or mismatch alternating words. The only real edge case is empty strings from consecutive spaces, which produce an empty firstLetter and rest, not the described every-other-word mangling.

1 Like