Function Parameters
Function parameters look simple but modern JS lets you do a lot at the signature: defaults, destructuring, rest, named arguments.
Default values
JS
function greet(name = "anonymous") {
return `Hi, ${name}!`;
}
// Default kicks in for undefined — NOT for null or "" or 0
greet(); // "Hi, anonymous!"
greet(undefined); // "Hi, anonymous!"
greet(null); // "Hi, null!"
greet(""); // "Hi, !"
Rest parameters — collect the rest into an array
JS
function sum(...nums) {
return nums.reduce((t, n) => t + n, 0);
}
sum(1, 2, 3, 4); // 10
// Rest can follow named params
function pickAll(first, ...others) { /* … */ }
Named arguments via destructuring
JS
function createUser({ name, role = "member", active = true } = {}) {
// ...
}
// Call site reads clearly
createUser({ name: "Ada", role: "admin" });
// Default `{}` lets you call with no arg
createUser();
Arguments inside the function
| What you have | How to access |
|---|---|
| Named param | By its name |
| All args (legacy) | arguments — array-like, not in arrow functions |
| All args (modern) | Rest parameter ...args |
| Function reference | The function's own name; arguments.callee is forbidden in strict mode |
Tip: For functions with more than three options, prefer a single options object:
createUser({ name, role }). Positional args become a guessing game once there are four or more.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from Function Parameters!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Add a default so callers can omit the role.
function createUser(name, role
'member') { /* … */ }
A single character — assignment.
Discussion
Loading…