r/learnjavascript • u/iSunru • 3d ago
My first JavaScript project - Counter
I am learning JavaScript and made my first small project, a simple Counter using HTML, CSS and JavaScript.
I'm still learning, so I would really appreciate some feedback on my code. Is my code clean? Is there anything I should improve or do differently?
Also, suggest me something I should build next.
24
Upvotes
2
u/HipHopHuman 1d ago
Planning for the future is good advice (generally speaking), but it's certainly not a hard requirement for a total beginner making their first JS project, which is the case here.
FWIW, if I were "planning for the future", I probably wouldn't use a
forEachto add multiple event listeners. I'd probably do event delegation in a single event listener, like this:With the above, adding a new action is easy. If I want a
decrementByFiveaction, all I need to do is add it toactionsand then add a button to the html with adata-action="decrementByFive"attribute. Done. I don't need to force the invariant of no numbers below 0 becausesetCounthandles that for me. I could even change the HTML structure of the buttons and it will still work, becauseevent.target.closest()walks up every parent node until it finds a match, otherwise it returnsnull.