Lesson · JavaScript Basics
Functions, parameters, and return values
A function names a task so it can be used and tested independently.
What you will learn
- Declare a function
- Pass arguments to parameters
- Return a result to the caller
Declare behavior
A function declaration gives a reusable operation a name. Its body does not run until a call invokes it. This separates the description of a task from the moments when the program needs to perform it.
Pass information in
Parameters are the names in a function definition; arguments are the values supplied in a call. A function that receives its inputs explicitly is easier to test than one that reads changing values from outer scope. Use names that explain the role of each argument.
Return a result
return sends a value back to the caller and ends that function call. console.log displays information but does not return it for further calculation. Return values let the caller decide whether to display, store, compare, or combine the result.
Handle boundaries
A function should have a clear expectation for its inputs. It may validate them, or its caller may guarantee them; document and test whichever contract you choose. Keep a function small enough that a reader can understand the result from its inputs and body.
Keep effects separate from calculations
A function that receives values and returns a result is easier to test than one that also changes unrelated page state. Some functions need side effects, such as updating the DOM, but make those actions explicit in the name and call site. This distinction helps you reason about what a function changes.
function totalWithTax(price, rate) {
return price + price * rate;
}
const total = totalWithTax(100, 0.1);
console.log(total);
Expected output
110
Practice exercise
Write a function that accepts a name and returns a greeting without logging inside the function.
Show a hint
Use a template literal with the parameter.
Show one possible solution
function greet(name) { return `Hello, ${name}!`; } then log greet('Ari') at the call site.
Quick check
A returned value can be reused in another expression; logging is a display side effect.