Academy · Beginner · 15 min

JavaScript basics: variables, functions and events

Learn the core of JavaScript by building a small calculator that reacts to clicks.

JavaScript makes pages interactive. Start with three ideas: variables, functions and events.

const bill = 2000; // a value you do not change let tipPercent = 10; // a value that can change function tip(amount, pct) { return amount * pct / 100; } console.log(tip(bill, tipPercent)); // 200

Responding to the user

document.getElementById("go").addEventListener("click", function () { const value = Number(document.getElementById("bill").value); document.getElementById("out").textContent = "Tip: " + tip(value, 10); });
  • const and let declare variables. Prefer const when the value will not change.
  • A function packages steps you can reuse.
  • An event listener runs your function when the user clicks, types or taps.
  • Use textContent, not innerHTML, when showing user input. It prevents script injection.

Try it

Open the tip calculator. Change the default percentage, then add a field for the number of people and split the total.

Common mistakes and practice

  • Using == instead of ===. The strict version avoids surprising type conversions.
  • Declaring everything with var. Use const by default and let when a value must change.
  • Defining a function but never calling it, or calling it before the page has loaded the element it needs.

Practice: Make a counter: a button that adds one to a number each time it is clicked, and a second button that resets it to zero.

Practice ideas after this lesson

Reading about code helps, but writing it is what teaches. Small projects that you actually use make the ideas stick, and each one reinforces variables, functions and conditions.

Aim for something tiny that you can finish in an evening, then add one feature at a time.

Practical tips

  • A tip calculator, a unit converter or a simple quiz.
  • A to-do list that saves to the browser.
  • A number guessing game with hints.
  • Write down what failed and how you fixed it. That is real learning.