Ticker

6/recent/ticker-posts

🧠 Default Parameters in JavaScript – Small Feature, Big Cleanup

🧠 Default Parameters in JavaScript – Small Feature, Big Cleanup

You’ve definitely written this before:

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

Works… until it doesn’t 😅

Pass an empty string? 0? false?

💀 Boom — your “default” kicks in when it shouldn’t.

That’s exactly why default parameters exist.

Cleaner, safer, and way less hacky.

⚡ What Default Parameters Actually Do

Simple idea:

👉 If a parameter is undefined, use a fallback value.

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

Now:

greet();        // Hello Guest
greet("John");  // Hello John

No extra logic. No hacks.

🔎 Important Detail (This Trips People Up)

Default values only apply when the argument is undefined.

function test(value = 10) {
  console.log(value);
}

test(undefined); // 10 ✅
test(null);      // null ❗
test(0);         // 0 ❗

👉 This is actually a good thing.

It avoids the classic || bug.

🔥 Real Use Case: API Config

function fetchData(url, method = "GET") {
  console.log(`Fetching ${url} with ${method}`);
}

Now:

fetchData("/users");          // GET
fetchData("/users", "POST");  // POST

Clean and predictable.

🔥 Using Functions as Default Values

You’re not limited to static values.

function generateId() {
  return Math.random().toString(36).slice(2);
}

function createUser(id = generateId()) {
  console.log(id);
}

👉 Default gets computed only when needed.

🔥 Default Params + Destructuring (Real-World Pattern)

function createUser({ name = "Guest", role = "user" } = {}) {
  console.log(name, role);
}

Why this is powerful:

  • Handles missing object
  • Handles missing properties
createUser(); // Guest user

👉 You’ll see this a lot in production code.

💡 Real Developer Insight

Default parameters replace a lot of old patterns like:

param = param || value;

But here’s the catch:

👉 That old pattern breaks valid values like 0, false, ""

Default parameters fix that.

Also:

👉 Keep defaults simple.

If your default logic is too complex… it probably belongs inside the function, not in the parameter.

⚠️ Common Developer Mistakes

1️⃣ Mixing || with default params

function test(value = 10) {
  value = value || 20; // ❌ confusing
}

Pick one approach.

2️⃣ Forgetting undefined rule

test(null); // won’t use default

3️⃣ Overloading parameters with logic

function test(value = someHeavyFunction()) { }

👉 Can make code harder to read.

4️⃣ Missing fallback for destructured params

function fn({ name }) {} // ❌ crash if undefined

Correct:

function fn({ name } = {}) {}

🚀 Best Practice Summary

✅ Use default parameters instead of || fallbacks
✅ Remember defaults apply only for undefined values
✅ Keep default values simple and predictable
✅ Use destructuring defaults for cleaner APIs
✅ Avoid mixing multiple fallback strategies

Reactions

Post a Comment

0 Comments