Spot the bug - #190: Textbox

A quirky text twist breaks unexpectedly.

<div id="wrapper">
  <input id="input" type="text" placeholder="type something" />
  <button id="btn">Animate</button>
  <p id="out"></p>
</div>

<script>
  const el = document.getElementById('out');
  const s = 0; // starting index
  document.getElementById('btn').addEventListener('click', () => {
    const val = document.getElementById('input').value;
    // bug: uses immutable string slice; expected to mutate and show reversed
    const res = val.slice(0, s + 3); // s is always 0, but bug is elsewhere
    el.textContent = res.split('').reverse().join('');
  });
</script>

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

The bug is that s is defined as a constant 0 and never updated, so the code always slices from 0 to 3 and then reverses, not progressively building or mutating the string. If the goal is to reverse the input progressively or show a growing slice, you should increment s or compute a dynamic end index based on user interaction. For a simple fix that reverses the whole input on each click, you can drop slice entirely and just reverse value:

const res = val;
el.textContent = res.split('').reverse().join('');

If you want a growing slice, keep s as a mutable counter outside the click handler and increment it on each click, then use val.slice(0, s). Also consider using let instead of const for s, and reset logic as needed.

Example quick fix (reverse entire input on click):

<div id="wrapper">
  <input id="input" type="text" placeholder="type something" />
  <button id="btn">Animate</button>
  <p id="out"></p>
</div>

<script>
  const el = document.getElementById('out');
  document.getElementById('btn').addEventListener('click', () => {
    const val = document.getElementById('input').value;
    el.textContent = val.split('').reverse().join('');
  });
</script>

If you want a growing slice, switch s to let and increment:

let s = 0;
document.getElementById('btn').addEventListener('click', () => {
  const val = document.getElementById('input').value;
  s = Math.min(val.length, s + 1);
  el.textContent = val.slice(0, s).split('').reverse().join('');
});