JS Functions
JavaScript Functions: Declarations, Expressions, and Parameters
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.
Function Declarations vs. Function Expressions
JavaScript gives you two classic ways to define named or variable-bound functions (plus arrow functions covered in a later lesson):
- Function declaration: Uses
function name(params) { ... }and is hoisted, so you can call it above its definition in the same scope. - Function expression: Stores a function inside a
constvariable (const fn = function(params) { ... }), which follows Temporal Dead Zone rules and is not hoisted as callable.
Default Parameters and Rest Parameters
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
Pure Functions and Early Returns
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.
Common Mistakes to Avoid
- Forgetting the
returnkeyword: A function without areturnstatement automatically returnsundefined. - Confusing function references with calls: Passing
handleClick()insideaddEventListenerruns it immediately instead of passinghandleClickas a reference. - Mutating input arrays or objects: Changing an array parameter directly causes unexpected side effects elsewhere in your app.
Frequently Asked Questions
What is the difference between parameters and arguments?
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).
What happens if I pass fewer arguments than parameters?
Any omitted parameter receives undefined, unless you assign a default value such as currency = "USD" in the parameter list.
Can a JavaScript function return multiple values?
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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.