Function declarations vs expressions
Packaging reusable steps into a named block of code.
Step 1
The idea
Imagine you need to make a cup of tea. The steps are: boil water → add teabag → pour water → wait → remove teabag → add milk. You'll do this every morning.
Instead of writing those steps out every time, you write them once and give them a name: makeTeа(). Then whenever you want tea, you just call that name.
That's a function. It's a named, reusable block of code. You define it once, call it whenever you need it.
Step 2
See it run
Test started: Login Flow
Test PASSED
---
Test started: Checkout Flow
Test FAILED
---
Test started: Search Flow
Test PASSED// Define the function once
function runTest(testName, passed) {
console.log(`Test started: ${testName}`);
if (passed) {
console.log("Test PASSED");
} else {
console.log("Test FAILED");
}
console.log("---");
}
// Call it as many times as needed
runTest("Login Flow", true);
runTest("Checkout Flow", false);
runTest("Search Flow", true);$ node functions.jsThe words inside the parentheses — testName and passed — are parameters. They're slots that get filled with real values each time the function is called.
Step 3
Now you try
Define a function called greetTester that takes a name parameter and prints: Welcome to the team, [name]!
Call it three times with different names. Then add a second parameter role and update the message to: Welcome, [name] — role: [role]
Step 4
Why a tester cares
Functions let you write logic once and reuse it everywhere. Here's a tax calculator — one function, called many times with different inputs:
function calculateTax(price, taxRate) {
const tax = price * (taxRate / 100);
const total = price + tax;
return { price, tax, total };
}
function printBill(item, price, taxRate) {
const bill = calculateTax(price, taxRate);
console.log(`${item}: ₹${bill.price} + ₹${bill.tax.toFixed(2)} tax = ₹${bill.total.toFixed(2)}`);
}
printBill("Laptop", 45000, 18);
printBill("Notebook", 120, 12);
printBill("Pen", 15, 5);$ node tax.jsLaptop: ₹45000 + ₹8100.00 tax = ₹53100.00
Notebook: ₹120 + ₹14.40 tax = ₹134.40
Pen: ₹15 + ₹0.75 tax = ₹15.75If the tax formula ever changes, you update one function — all three bills update automatically. This is why functions are the most important concept in programming.
Recap
- 1A function is a named block of reusable code: function name(params) { ... }
- 2Parameters are slots filled with real values each time the function is called.
- 3Functions eliminate repetition — define once, use everywhere.