JavaScript Functions: Parameters and Return Values
A JavaScript function is a reusable block of code. Give it a clear name, pass information through parameters and return a result when needed.
Declare a function
function greet(name) {
return "Hello, " + name + "!";
}
const message = greet("Aadil");
Here, name is a parameter. Calling greet("Aadil") passes an argument, and the function returns a string.
Use an arrow function
const add = (first, second) => {
return first + second;
};
const total = add(3, 4);
For a short expression, an arrow function can return the value directly:
const double = number => number * 2;
Keep functions focused
A function is easier to understand when it performs one clear job. Use meaningful names and return values rather than relying on unexpected changes elsewhere in the page.
Choose parameters and return a result
Parameters are the named inputs in a function definition. The values supplied when you call the function are arguments. A default parameter provides a fallback when an argument is omitted.
function calculateTotal(price, quantity = 1) {
return price * quantity;
}
const oneItem = calculateTotal(12);
const threeItems = calculateTotal(12, 3);
return sends a value back to the caller and ends that function call. Use it when later code needs the result. console.log() only writes a value to the developer console; it does not return that value.
Pass a function to an event
Functions can be passed to other code as values. For example, an event listener can call a function when a user clicks a button:
const button = document.querySelector("#save-button");
const status = document.querySelector("#status");
function showMessage() {
status.textContent = "Saved";
}
button.addEventListener("click", showMessage);
Pass the function name without parentheses when you want the event listener to call it later. Writing showMessage() would call it immediately.
Keep inputs and side effects clear
Functions are easier to reuse when they receive the values they need through parameters and return their results explicitly. Keep unrelated page updates, network requests, and calculations in separate functions when that makes each task easier to understand.
JavaScript function questions
Are parameters and arguments the same?
They are related but different: parameters are the names listed in the function definition, while arguments are the values passed to the function call.
When should a function return a value?
Return a value when the calling code needs to store it, display it, or use it in another calculation. A function can also perform an action without returning a useful value.