Functions
Reusable blocks of code you can run any time. Functions are the heart of every program.
What you will learn
- Define and call a function
- Pass parameters and return values
- Reuse logic instead of repeating it
Define once, use many times
A function is a named block of code you can run whenever you want. Define it with function, then call it with its name and ().
<script>
function greet() {
document.write("Hello, CodingClave!<br>");
}
greet(); // call it
greet(); // call again
</script>The function greet() { ... } part only defines the recipe — nothing happens yet. Each greet() line below actually runs it. Because we call it twice, the message is written twice.
Note: Output: Hello, CodingClave! Hello, CodingClave!
Parameters and return
Parameters let you pass data in. return sends a result back out.
<script>
function add(a, b) {
return a + b;
}
let result = add(5, 3);
document.write("5 + 3 = " + result);
</script>add has two parameters, a and b — empty slots for incoming numbers. When we call add(5, 3), a becomes 5 and b becomes 3, and return a + b sends 8 back. That returned 8 lands in result, which we then print.
Note: Output: 5 + 3 = 8
The real power is reuse: the same function gives different answers for different inputs.
<script>
function greet(name) {
return "Hello, " + name + "!";
}
document.write(greet("Asha") + "<br>");
document.write(greet("Ravi"));
</script>greet("Asha") runs the function with name set to "Asha", returning "Hello, Asha!". The second call passes "Ravi", returning "Hello, Ravi!". One recipe, two different results — that is why functions save so much repeated typing.
Note: Output: Hello, Asha! Hello, Ravi!
Tip: Functions follow DRY — Do not Repeat Yourself. If you write the same lines twice, wrap them in a function and call it instead.
Q. What does the return keyword do?
✍️ Practice
- Write a function
square(n)that returnsn * nand call it with three numbers. - Write a
greet(name)function and call it for three people.
🏠 Homework
- Write a function that takes a price and a quantity and returns the total cost.