A function is a reusable block of code. Write it once, call it many times.
Declare and call
function greet(name) {
return 'Hello ' + name;
}
greet('Asha'); // 'Hello Asha'
nameis a parameter (a placeholder)'Asha'is an argument (the real value)returnsends a value back and stops the function
Default parameters
function greet(name = 'Guest') { ... }
Function expression
const square = function (n) { return n * n; };
Why use functions?
- Avoid repeating code
- Give a name to a task, making code easier to read
- Test and fix one piece at a time
Example
Example — Function with parameters and return
HTML
<pre id="out"></pre>
<script>
function calcTotal(price, qty = 1, gst = 18) {
const subtotal = price * qty;
return subtotal + subtotal * gst / 100;
}
document.getElementById('out').textContent =
'Pen x 1: ₹' + calcTotal(10) + '\n' +
'Book x 3: ₹' + calcTotal(200, 3) + '\n' +
'Bag x 2 (12% GST): ₹' + calcTotal(500, 2, 12);
</script>