DEV Community

Discussion on: Search through a JSON object using JavaScript

Collapse
 
killants profile image
killants • Edited

Not used to see many arrow function (without being small ones, in array.map for example) so i got a bit confused with the parameter line :
{ searchKeys = typeof searchValue === "string", maxDepth = 20 } = {}

Would you mind to explain in a few words why it is there? :)

Thank you in advance.

Thread Thread
 
qm3ster profile image
Mihail Malo

Sure, this doesn't depend on it being an arrow function, can be in a function just as well.

This is the equivalent function:

function fn(arg) {
  if (arg === undefined) arg = {}
  let searchKeys = arg.searchKeys
  if (searchKeys === undefined) searchKeys = typeof searchValue === "string"
  let maxDepth = arg.maxDepth
  if (maxDepth === undefined) maxDepth = 20
  /* ... */
}

First, we replace the point access with destructuring:

function fn(arg) {
  if (arg === undefined) arg = {}
  let { searchKeys, maxDepth } = arg
  if (searchKeys === undefined) searchKeys = typeof searchValue === "string"
  if (maxDepth === undefined) maxDepth = 20
  /* ... */
}

Next, we replace the conditional expressions for defaults with defaults in destructuring AND default in parameter:

function fn(arg = {}) {
  const { // we can use const now because we won't be reassigning
    searchKeys = typeof searchValue === "string",
    maxDepth = 20
  } = arg
  /* ... */
}

Finally, to avoid having to think of a name for the short-lived arg binding, we can just YEET it right into the parameter list:

function fn({
  searchKeys = typeof searchValue === "string",
  maxDepth = 20
} = {}) {
  /* ... */
}

We could write it like this:

function fn(
  { 
    searchKeys = typeof searchValue === "string",
    maxDepth = 20
  } = {
    searchKeys: typeof searchValue === "string",
    maxDepth: 20
  }
) {
  /* ... */
}

But that's just more verbose. Destructuring an empty object (if undefined is provided) is perfectly adequate, and gives defaults for all keys.

function fn(
  searchValue, // this is the v below that we are depending on, it has to come first.
  { searchKeys = typeof searchValue === "string", maxDepth = 20 } = {}
) {
  /* ... */
}