Named object parameters in ES6. How can I verify that they are provided?

I have ES6 code where I am passing some named parameters of a specific object with parameters, like ...

    configureMapManager({ mapLocation, configuredWithDataCallback, locationHasChanged })
{
    if (mapLocation) console.log(mapLocation)
}

      

This is a contrived case and the following calls will work fine ...

configureMapManager({ mapLocation: "BS1 3TQ" })
configureMapManager({})

      

But it will explode ...

configureMapManager()

      

... because I cannot verify that the passed object is defined (this is not because I called the method without any parameters). How can I do this without rewriting it like this (which sucks because then you lose the visibility of the allowed parameters inside the object) ...

    configureMapManager(options)
{
    if (options && options.mapLocation) console.log(mapLocation)
}

      

+3


source to share


1 answer


Use default parameter:

function configureMapManager({ mapLocation } = {})
{
  console.log(mapLocation);
}

      



When the function is called without any parameters, it mapLocation

will be undefined:

configureMapManager(); // prints: undefined
configureMapManager({ mapLocation: 'data' }); // prints: data

      

+4


source







All Articles