A JavaScript function is a reusable block of code designed to perform a specific task when called. Functions accept input arguments, run local logic, and return a computed result back to the caller.
JavaScript gives you two classic ways to define named or variable-bound functions (plus arrow functions covered in a later lesson):
function name(params) { ... } and is hoisted, so you can call it above its definition in the same scope.const variable (const fn = function(params) { ... }), which follows Temporal Dead Zone rules and is not hoisted as callable.ES6 lets you give parameters default values when an argument is omitted or undefined, and collect extra arguments into an array with ...rest.
function formatPrice(amount, currency = "USD") {
return `${currency} ${amount.toFixed(2)}`;
}
function sumAll(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(formatPrice(19.5)); // "USD 19.50"
console.log(formatPrice(19.5, "EUR")); // "EUR 19.50"
console.log("Sum:", sumAll(4, 8, 15)); // 27
Return early when inputs are invalid instead of wrapping your entire function body inside nested if...else blocks. Keeping functions small and returning new values without mutating global state makes testing effortless.
return keyword: A function without a return statement automatically returns undefined.handleClick() inside addEventListener runs it immediately instead of passing handleClick as a reference.Parameters are the named placeholders listed in a function definition, like (a, b). Arguments are the real values you pass when calling the function, like add(3, 5).
Any omitted parameter receives undefined, unless you assign a default value such as currency = "USD" in the parameter list.
A function returns one value, so wrap multiple results in an object { min, max } or an array [min, max] and destructure them on the calling side.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.