Functions: Inputs, Reusability & Return Values
Quick Overview
A function with no `return` gives back `undefined`, not nothing. Arguments are copied in, so reassigning a parameter changes only the local copy unless it is an object, where the reference is shared.
Deep Dive
1. Reusable Recipe Blocks
A function is a block of reusable code designed to perform a specific task when invoked (called).
2. Why It Matters
Functions eliminate repetitive copy-pasting, isolate complex business rules into modular building blocks, and allow code to process dynamic arguments.
3. Parameters vs. Arguments & The return Keyword
- Parameters: Variable placeholders listed inside the function declaration.
- Arguments: Actual values passed into the function when called.
return: Exits the function execution and passes the computed output back to the caller.
// Function Declaration with parameters (length, width)
function calculateArea(length, width) {
const area = length * width;
return area; // Explicit return value
}
// Invocation with arguments (10, 5)
const roomArea = calculateArea(10, 5);
console.log(roomArea); // 50
4. Default Parameters
Provide fallback values for parameters in case arguments are omitted during invocation:
function greetUser(name = "Guest", role = "Member") {
return `Welcome, ${name}! Role: ${role}.`;
}
console.log(greetUser()); // "Welcome, Guest! Role: Member."
console.log(greetUser("Sarah", "Admin")); // "Welcome, Sarah! Role: Admin."
5. Common Mistakes
- Forgetting the
returnKeyword: If a function does not contain an explicitreturnstatement, JavaScript automatically returnsundefinedwhen invoked! - Confusing Function Declaration with Execution: Defining a function
function doSomething() {}does NOT run the code inside it. You must explicitly invoke it:doSomething().
6. Try It Yourself
Write it yourself. The tests below run against your code.
Write Double Number Function
Examples
7. Next Steps
Always ensure utility functions return explicit results. Next, let's peek under the hood at how JavaScript executes code using Execution Contexts!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.