JavaScript Functions Deep Dive#4: Default Parameters, Rest, and arguments – Writing Flexible, Modern Functions

pushpesh kumarpushpesh kumar
4 min read

Modern JavaScript empowers us to write functions that are safer, cleaner, and more flexible. Three features that make this possible are:

  • Default parameters

  • Rest parameters and the spread operator

  • The evolution from arguments to ...rest

Let’s explore how these tools help create reliable, reusable code, and where you should prefer one over the other.


1️⃣ Default Parameters — Safe Fallbacks for Arguments

🔹 What It Is

Default parameters allow you to provide a value in case the function is called without that argument or with undefined.

function greet(name = "Guest") {
  return `Hello, ${name}`;
}

console.log(greet("Alice")); // Hello, Alice
console.log(greet());        // Hello, Guest

✅ Language Rules

BehaviorExample
Only triggers when argument is undefinedgreet(null) → "Hello, null"
Can use other parameters as defaultsfunction say(msg, name = msg)
Evaluated at call time, not definition timeUseful for dynamic defaults

❗ Common Pitfall

function greet(name = "Guest") {
  console.log(`Hello, ${name}`);
}
greet(null); // ⚠️ "Hello, null", not "Hello, Guest"

Default only applies when value is undefined, not falsy (like null, 0, false).


2️⃣ Rest Parameters — Collect Extra Arguments into an Array

🔹 What It Is

Use ...rest to gather all remaining arguments into a real array.

function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20));  // 30

🔹 Multiple Parameters with Rest

function logInfo(level, ...messages) {
  console.log(`[${level}]`, messages);
}
logInfo("INFO", "Server started", "on port 8080");

3️⃣ Spread Operator — Expanding Arrays into Individual Elements

The same ... operator behaves differently when used in a function call or array literal.

🔹 Spread in Function Calls

const values = [1, 2, 3];
console.log(Math.max(...values)); // 3

🔹 Spread in Arrays

const a = [1, 2];
const b = [3, 4];
const combined = [...a, ...b]; // [1, 2, 3, 4]

4️⃣ arguments Object vs Rest Parameters

🔹 What is arguments?

  • Built-in array-like object in regular functions

  • Contains all arguments passed, regardless of parameters

function showArgs() {
  console.log(arguments); // [1, 2, 3]
}
showArgs(1, 2, 3);

❌ Limitations of arguments

LimitationExplanation
❌ Not a real arrayCan’t use map, filter, etc.
❌ Not available in arrow functionsOnly works in traditional function
❌ Not always intuitiveIncludes all arguments, even unused ones

✅ Prefer Rest Parameters

const showArgs = (...args) => {
  console.log(args); // [1, 2, 3]
};

✅ You get a true array, cleaner syntax, and it works in arrow functions.


🧪 Comparison Table

Featurearguments...rest
TypeArray-like objectReal array
Works in arrow func?❌ No✅ Yes
Clean syntax❌ Verbose✅ Modern
Preferred usageLegacy or special cases✅ Always prefer

✅ Recap: Best Practices

Use CaseWhat to Use
Provide default valuesfunction(name = "Guest")
Capture all argsfunction(...args)
Expand array into argsMath.max(...nums)
Modern, flexible functionsUse ...rest + default params
Legacy or strict APIsMay still see arguments

📦 Real-World Examples

🔸 Logging Utility with Default and Rest

function log(level = "INFO", ...messages) {
  console.log(`[${level}]`, ...messages);
}
log("ERROR", "Something went wrong", "at line 23");
log(undefined, "Default level used");

🔸 Destructuring with Rest

const [first, ...rest] = [1, 2, 3, 4];
console.log(first); // 1
console.log(rest);  // [2, 3, 4]

🏁 Final Thoughts

Default values, rest parameters, and the spread operator bring clarity and power to JavaScript functions. Combined with arrow functions, they let you write modern, minimal, and expressive code.

If you're still using arguments, it's time to upgrade — the ...rest operator is not only more powerful but also more predictable.

0
Subscribe to my newsletter

Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

pushpesh kumar
pushpesh kumar