Functions
A function is a reusable block of code with a name. It can take parameters (inputs) and return a result.
Functions are the building blocks of every JavaScript program. Instead of one long list of instructions, you split the work into small named jobs: calculateTotal(), showCart(), validateEmail(). Each one can be tested and reused, and the code reads almost like a description of what the page does.
Parameters are the inputs a function needs; return hands back the answer. A function that returns a value can be used inside other expressions, like addGst(price, 18) * qty. Functions are also how you respond to events: you give a function to a button, and the browser calls it on every click.
function addGst(price, rate) {
return price + price * rate / 100;
}
addGst(1000, 18); // 1180You can also write short functions as arrow functions:
const square = (n) => n * n;Arrow functions are a shorter way to write the same thing, and they're very common in modern code - especially as small helper functions passed to methods like map and filter, which you'll see in the next lesson.
<!DOCTYPE html>
<html>
<body>
<label>Price: <input id="price" type="number" value="1000"></label>
<label>Discount %: <input id="off" type="number" value="15"></label>
<button onclick="show()">Calculate</button>
<p id="out"></p>
<script>
function discounted(price, percent) {
return Math.round(price - price * percent / 100);
}
function show() {
const p = Number(document.getElementById("price").value);
const d = Number(document.getElementById("off").value);
document.getElementById("out").textContent = "You pay Rs " + discounted(p, d);
}
</script>
</body>
</html>▶ Try it yourselfcalculateTotal or showError.- A function is a named, reusable block: inputs (parameters) -> output (return).
- Arrow functions are a short form:
(n) => n * n. - Small functions that do one job are easier to test and reuse.
