Create a Counter in JavaScript in Five Steps
Introduction
Problem Solving
Step 1: Create the Interface
First, define a counter
block that displays the current number and contains a container buttonGroup
with buttons for “subtract, reset, and add.”
Step 2: Select Screen Elements
Use the previously defined id
attributes to select each DOM element (using the getElementById method) and store them in variables.
Step 3: Render Data on the Screen
Currently, the counterDisplay
has no content, so we can define a piece of data and render it on the screen; since “rendering data on the screen” is a highly repetitive action, we can isolate it into a function to call when needed.
Step 4: Listen for Events
The data is now correctly displayed on the screen, but the buttons have no functionality yet. The next step is to listen for button click events and execute the corresponding functions upon clicking; use eventListener to listen for “click” events.
In other words, you can achieve the functionality of three eventListeners
with a single eventListener
by checking the id (e.target.id) of the clicked event target and performing the corresponding action based on that.
Step 5: Manipulating Data
Next, we need to implement the functionality for each button. Here, we define three functions: “add, subtract, and reset.”
Conclusion
From this simple exercise, we have separated data from logic. This separation makes it easier to maintain the code and allows other developers to read and modify it more easily.
This is a simple example, but there are still many things to think about and improve upon, such as: “How can the code be made reusable?” “How can the code be made predictable and testable?” These are all worthwhile questions to consider.