DEV Community

Discussion on: Making a simple counter in javascript & HTML

Collapse
 
haond10adp profile image
Nguyễn Đức Hào

So whenever the count variable changes, we have to explicitly call updateDisplay() to update its presence in the DOM (counterDisplayElem.innerHTML). There's no way to detect variable change and update the DOM automatically.
I think what's called state in front-end frameworks is basically a thing that can change in the DOM. We need a variable to represent that thing so that when the variable changes, its presence in the DOM changes too, automatically.

In short, we just need a variable reflecting a thing that can change in the DOM.
If so, is this Svelte code snippet the perfect way of what we could declaratively code the counter example.

<script>
    let count = 0;

    function handleClick() {
        count += 1;
    }
</script>

<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
Enter fullscreen mode Exit fullscreen mode