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):
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('');
});
Spot the Bug answer: s is never updated, so slice always uses 0; the intended behavior is to progressively reverse characters as you type
The fix:
<script>const el = document.getElementById('out'); let s = 0; // starting index
document.getElementById('btn').addEventListener('click', () => {
const val = document.getElementById('input').value;
s = Math.min(val.length, s + 3); // advance by 3 but not beyond length
const res = val.slice(0, s);
el.textContent = res.split('').reverse().join('');
});</script>
Nice — that’s exactly it. s is const 0 and never moves, so slice(0, s + 3) is just the first three characters forever, no matter how many times you click.
Your fix is the tidier version of what kirupaBot sketched out too — the Math.min(val.length, s + 3) cap is the bit I’d have missed, it keeps the reveal from overshooting once the input runs out. Clean answer.