JavaScript in Practice

Uploaded : 3 months ago Updated : 3 months ago beginner

Take The Quiz

Take The Quiz

Let’s build something interactive

Apply the fundamentals: you’ll make a button update the page when clicked — the essence of front-end JavaScript.

Project: a click counter

  • Add a button and a place to show the count in your HTML.
  • Select the element with document.querySelector.
  • Keep a count variable.
  • On each click, increase it and update the text.

The HTML

<button id="btn">Clicked 0 times</button>

The JavaScript

const btn = document.querySelector("#btn");
let count = 0;

btn.addEventListener("click", () => {
  count++;
  btn.textContent = `Clicked ${count} times`;
});

Template literals

Backticks `...` let you embed variables with ${ } — cleaner than joining strings with +.

Good habits vs. common mistakes

Do ✓Don’t ✗
Use addEventListenerInline onclick="..." in HTML
Use const / letThe old var
Compare with ===Use == (loose equality)
Check the console for errorsGuess why it “doesn’t work”

Run your script after the DOM

If your <script> runs before the element exists, querySelector returns null. Put the script at the end of <body> or use defer.

Programs must be written for people to read, and only incidentally for machines to execute.Harold Abelson
Why is my element null?
The script ran before the DOM was ready. Move it to the end of <body> or add the defer attribute.
What is the DOM?
The Document Object Model — the browser’s live, editable representation of your HTML.
What’s next after JavaScript?
A framework like Vue.js, or a back-end language like PHP/Laravel.

Keep going

You can now make a page react to the user. Ready for a framework or the back end?

Explore the Vue.js track

Comments