Introduction to functions
A function is a named, reusable block of code that performs a task. You define it once, then run it, or "call" it, whenever you need that task done, optionally giving it input values and getting a result back. Functions are how JavaScript programs avoid repetition and break big problems into small, understandable steps. Almost everything you build later, from event handlers to React components, is a function.
Defining and calling
A function declaration has the keyword function, a name, a list of parameters in parentheses, and a body in curly braces. Defining it does not run it. To run it, write its name followed by parentheses.
function calculateTotal(price, quantity, taxRate = 0.18) {
const subtotal = price * quantity;
const total = subtotal + subtotal * taxRate;
return Math.round(total);
}
const bill = calculateTotal(250, 3); // 885
const exempt = calculateTotal(250, 3, 0); // 750
console.log(bill, exempt);
function sayHello() {
console.log('Hello!');
}
const result = sayHello(); // prints Hello!
console.log(result); // undefined: nothing was returned
Parameters, arguments and return values
Parameters are the names listed in the definition, like price and quantity. Arguments are the actual values passed when calling, like 250 and 3. Inside the function, each parameter works like a local variable holding its argument.
JavaScript is relaxed about counts. If you pass fewer arguments than parameters, the missing ones are undefined, unless you give a default value such as taxRate = 0.18. Extra arguments are ignored, though they can be collected with rest parameters, which you will meet soon.
The return statement sends a value back to the caller and immediately ends the function. Any code after a return in the same block never runs. A function without return, like sayHello, gives back undefined. Printing with console.log is not the same as returning: logging only displays a value, while returning lets other code use it.
Why functions make code better
- No repetition: write the tax calculation once and use it on every product.
- One place to fix: if the tax rule changes, you edit one function.
- Readable names:
calculateTotal(250, 3)explains itself better than the maths inline. - Testable pieces: a function that takes inputs and returns an output is easy to check.
A good habit is giving functions verb-based names that describe what they do, such as formatDate, isValidEmail or fetchUsers, and keeping each one focused on a single job.
Calling versus referring
The parentheses make all the difference. calculateTotal on its own is a reference to the function, a value you can store or pass around. calculateTotal() runs it. This matters with events: button.addEventListener('click', sayHello) passes the function so the browser can call it later. Writing sayHello() there would run it immediately during setup and pass its return value, undefined, as the listener, so clicks do nothing.
Another early stumble is forgetting return and then wondering why a variable is undefined. If a function computes something you need, make sure it returns it.
A note on hoisting
Function declarations are hoisted, meaning you can call them on a line above where they are written in the file. Functions stored in variables, such as const greet = function () {...}, are not usable before that line. The upcoming lessons on function definitions and arrow functions cover these forms.
Main points
Define a function once, call it with parentheses, pass data in as arguments, and use return to hand a result back. Small, well-named functions are the building blocks of every program you will write from here on.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.