Lesson 4 of 5 18 min read
JavaScript variables, functions and events
Add behaviour to web pages with JavaScript variables, functions, the DOM and event listeners.
In this lesson you will
- Declare variables with let and const and work with common value types
- Write functions, including arrow functions
- Select page elements and respond to user events with addEventListener
Adding JavaScript to a page
Put your script in a separate file and load it at the end of the <body> (or in the <head> with defer), so the HTML exists before the script runs:
<script src="app.js" defer></script>You can experiment instantly in the Console panel of the browser's developer tools.
Variables
const siteName = "DevCrest"; // cannot be reassigned
let visits = 0; // can change
visits = visits + 1;
const isMember = true; // boolean
const price = 499.5; // number (one type for whole and decimal numbers)
const skills = ["HTML", "CSS", "JavaScript"]; // array
const student = { name: "Kiran", year: 2 }; // object
console.log(`${student.name} knows ${skills.length} skills`); // Kiran knows 3 skills- Use
constby default andletwhen the value must change. Avoid the oldervar. - Text wrapped in backticks is a template literal:
${...}inserts a value into the string. - JavaScript is dynamically typed: the same variable could hold a number and later a string, which is flexible but means you must be careful.
Comparisons in JavaScript should use === (strict equality), which checks both value and type. "5" == 5 is true because of type conversion, while "5" === 5 is false.
Functions
function greet(name) {
return `Hello, ${name}!`;
}
const square = (n) => n * n; // arrow function
console.log(greet("Asha")); // Hello, Asha!
console.log(square(6)); // 36Arrow functions are a shorter syntax that is especially handy for small functions passed to other functions.
The DOM: JavaScript's view of the page
When the browser loads HTML, it builds the Document Object Model (DOM), a tree of objects representing every element. JavaScript reads and changes the page through the DOM:
document (contains html (contains head (contains title), body (contains h1, div.card, div.card)))
const heading = document.querySelector("h1"); // first <h1>
heading.textContent = "Welcome to my page";
const cards = document.querySelectorAll(".card"); // all elements with class "card"
cards.forEach((card) => card.classList.add("visible"));querySelector takes the same selectors you learned in CSS.
Responding to events
An event is something that happens on the page: a click, a key press, a form submission. You attach a function, called an event listener or handler, that runs when the event occurs.
<p>Likes: <span id="count">0</span></p>
<button id="like" type="button">Like</button>const button = document.querySelector("#like");
const countEl = document.querySelector("#count");
let likes = 0;
button.addEventListener("click", () => {
likes++;
countEl.textContent = likes;
});Walk through it: the script finds the button and the counter once, keeps the count in a variable, and registers a function to run on every click. Each click increases likes and updates the text on the page.
Hands-on exercise
Add a "Toggle theme" button to your personal page. When clicked, it should add or remove a class named dark on the body using document.body.classList.toggle("dark"). In your CSS, write a .dark rule that changes the background and text colours. As a bonus, change the button's text to "Light mode" or "Dark mode" depending on the current state.
Knowledge check
3 questions • 70% to pass • Practice only, no certificate
Key concepts
- Use const by default, let for values that change, and === for comparisons.
- Functions package reusable logic; arrow functions are a concise alternative syntax.
- The DOM is the browser's object model of the page; querySelector finds elements with CSS selectors.
- addEventListener runs a function whenever an event such as a click happens.
