2

The title is explanatory enough, here is an example of such a case:

const handleDateChange = useCallback((startDate = defaultStartDate, endDate = defaultEndDate) => {
      // Do something
}, [defaultStartDate, defaultEndDate]);

Do defaultStartDate and defaultEndDate need to be included in the dependency array (like in my example)?

1 Answer 1

2

Yes, because they're referenced by the function, so the previous version of the function referencing the old values cannot be reused when the values change. It's just like using those variables in the function body.

Your handleDateChange is effectively¹ the same as this, which makes it more obvious why you need those defaults in the dependency array:

const handleDateChange = useCallback(
    (startDate, endDate) => {
        if (startDate === undefined) {
            startDate = defaultStartDate;
        }
        if (endDate === undefined) {
            endDate = defaultEndDate;
        }
        // Do something
    },
    [defaultStartDate, defaultEndDate]
);

In a comment, you've asked:

In your code snippet you reassign the parameter in de body, in my example i do it in the parameters. Doesn't reassigning have different behaviour? Just like how Nullish coalescing (??) for example is different in this case?

No, the above is how default parameter values work. They're evaluated (if needed) during the call to the function, not (for instance) when the function is created. The JavaScript engine inserts code at the very beginning of your function (in a wrapper scope; details) that does the if and assignment above. (It's very similar to nullish coalescing, but null doesn't trigger the default, only undefined does, as in the code above). Here's an example:

function alloc() {
    const value = Math.random();
    console.log(`alloc called, returning ${value}`);
    return value;
}

function example(p = alloc()) {
    console.log(`p = ${p}`);
}

console.log("Call with a value other than `undefined` (no call to `alloc`):");
example(42);
console.log();

console.log("Call without a value (calls `alloc`):");
example();
console.log();

console.log("Call with `undefined` (also calls `alloc`):");
example(undefined);
console.log();

console.log("Call with `null` (doesn't call `alloc`):");
example(null);
.as-console-wrapper {
    max-height: 100% !important;
}


¹ "effectively" — There are two minor differences:

  1. the length property of your function using default parameter values is 0, whereas it's 2 in my rewrite.
  2. There's a wrapper scope involved that I haven't tried to replicate in this simple example (see my answer here for details). But the above is fundamentally how they work.*

FWIW, here's a small excerpt from the part of my book JavaScript: The New Toys where I explain the parameter scope:

LISTING 3-3: Defaults can’t refer to things in the function body—default-access-body.js
function example(value = x) {
var x = 42;
console.log(value);
}
example(); // ReferenceError: x is not defined
I’ve used var there because it doesn’t have the Temporal Dead Zone; it’s hoisted to the top of the
scope where it’s declared. But the default value expression still couldn’t use it. The reason is that
defaults are evaluated in their own scope, which exists between the scope containing the function and
the scope inside the function, see Figure 3-1. It’s as though the function were wrapped in another
function that handled doing the defaults.

4
  • In your code snippet you reassign the parameter in de body, in my example i do it in the parameters. Doesn't reassigning have different behaviour? Just like how Nullish coalescing (??) for example is different in this case?
    – Mees
    Jan 16 at 9:22
  • @Mees - I've updated the answer to answer the question in your comment. :-) Happy coding! Jan 16 at 9:30
  • @T.J.Crowder can you add few words what you mean with "mini-scope" above? Jan 16 at 9:53
  • 1
    @GiorgiMoniava - I shouldn't have called it a "mini-scope" (though its actual contents are quite small in most cases). Using default parameter values creates a wrapper scope between the outer scope and the function scope. I describe it in my answer here and in the Defaults Are Evaluated In Their Own Scope section of Chapter 3 of my book. Jan 16 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.