Repeat until a condition is met, when the number of iterations is not known in advance.
A repayment schedule has as many rows as it takes to clear the balance. Nothing in the data says how many that is, so the template counts them out itself.
<style>
body { font: 14px/1.5 system-ui, sans-serif; margin: 0; color: #24292f; }
table { border-collapse: collapse; width: 100%; max-width: 28em; }
th, td { padding: 5px 10px; text-align: right; border-bottom: 1px solid #eaeef2; font-variant-numeric: tabular-nums; }
th { font-weight: 600; background: #f6f8fa; }
th:first-child, td:first-child { text-align: left; }
tr:last-child td { font-weight: 700; }
</style>
<script type="text/template" id="schedule">
#{ let balance = principal; let period = 0; let paid = 0; }#
<table>
<thead>
<tr><th>Period</th><th>Payment</th><th>Remaining</th></tr>
</thead>
<tbody>
#while(balance > 0) {#
#{ period++; }#
#{ let payment = Math.min(instalment, balance); balance -= payment; paid += payment; }#
<tr>
<td>#period#</td>
<td>#payment#</td>
<td>#balance#</td>
</tr>
#}#
<tr><td>#period# periods</td><td>#paid#</td><td>0</td></tr>
</tbody>
</table>
</script>
<div id="output"></div>
<script src="https://cdn.jsdelivr.net/gh/richdafunk/hashJS@v1.3.6/hashJS.js"></script>
<script>
// The number of rows is not known before rendering: it falls out of the
// data. That is the case a while loop exists for.
const data = {
principal: 12000,
instalment: 2500
};
new hashJS('schedule', data, 'output');
</script> This is the case a while loop is for. A for…of loop needs a collection to walk; here the collection does not exist until the loop has produced it.
The loop condition and the body both read and write balance, a variable declared in a statement block above the table. Rendering is a single pass, so the value the last row prints is the value the summary row sees afterwards.
A template that loops on a condition can loop forever, exactly as it can in a .js file. Here the balance strictly decreases by Math.min(instalment, balance), which cannot be zero while the balance is positive.