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);
});
constandletdeclare variables. Preferconstwhen 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, notinnerHTML, 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.