One job only
A good function has one clear job. You should be able to name it with a verb phrase like formatPrice, findTopScore, or buildStudentCard.
If the name needs “and”, split the function. This makes your hackathon repo easier to read during judging or internship review.
Why functions matter
Functions turn repeated code into a reusable tool. Instead of copying the same 8 lines in three places, you write it once and call it when needed.
This also makes testing easier. You can pass sample data into a function and check the returned result before connecting it to the page or an API.
Start with data
Keep the function focused on input and output. Do not make it depend on random outside variables unless it has to.
This example takes an order object and returns a display string for a UPI-style payment summary.
const order = {
id: "ORD-104",
customer: "Asha",
amount: 249,
paid: true
};
function formatPaymentStatus(order) {
if (order.paid) {
return `${order.customer} paid ₹${order.amount}`;
}
return `${order.customer} has not paid yet`;
}
console.log(formatPaymentStatus(order));Parameters beat guessing
A parameter is the value a function asks for. An argument is the actual value you pass when you call it.
Use parameters instead of making the function read from a variable outside. Then the function is easier to reuse in another file later.
Avoid global leaks
A global variable is available everywhere in the file. It feels easy, but it can create bugs when two functions change the same value.
Prefer const and let inside the smallest useful scope. If a value belongs only inside a function, declare it inside that function.
let total = 0; // Avoid using this as shared state unless needed
function addToCart(price) {
const updatedTotal = total + price;
return updatedTotal;
}
console.log(addToCart(99));Return, do not print
console.log is useful while checking your work. But most functions should return a value, not just print it.
A returned value can be used by another function, shown on a page, saved in an object, or sent later with fetch.
Scope in practice
Variables declared inside a function cannot be used outside it. That is function scope.
Variables declared inside if, for, or other blocks with const or let stay inside that block. That is block scope.
function getPassMessage(score) {
const passingScore = 40;
if (score >= passingScore) {
const message = "Passed";
return message;
}
return "Try again";
}
console.log(getPassMessage(72));
// console.log(message); // Error: message is not available hereDo this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done