Counter Patterns with Event

Variable Review

Variables store information. The variable is defined on the let hand side of the expression, and the value is set on the right side.

We would read this expression like so:

*The variable score gets the value 3

Counter Pattern with Event

Name Code (Block) Code (Text)
Counter Pattern with Event
var myVar = 0;

onEvent("id", "click", function(event) {
    myVar = myVar + 1;
});

The model could be read like so:

The variable myVar gets the value 0. When the onEvent is triggered by a click the variable is updated. myVar now gets the current value of myVar and adds one to it. The new value is then stored in myVar.

How does it work?

When the event is triggered, the variable is updated. The current value of the variable is increased or decreased by a set amount. The new value is stored in the variable.

Examples


The variable score gets the value 0. When the onEvent is triggered by a click on the button, the variable is updated. score now gets the current value of score and adds one to it. The new value is then stored in score. The score is then displayed on the screen.


The variable score gets the value 50. When the onEvent is triggered by a click on the button, the variable is updated. score now gets the current value of score and subtracts three from it. The new value is then stored in score. The score is then displayed on the screen.

Found a bug in the documentation? Let us know at documentation@code.org