Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object equals another object syntax

There is a function in the testing section in the redux docs and I’m trying to figure out what this syntax means.

export function renderWithProviders(
  ui,
  {
    preloadedState = {},
    // Automatically create a store instance if no store was passed in
    store = setupStore(preloadedState),
    ...renderOptions
  } = {}
) {
  function Wrapper({ children }) {
    return <Provider store={store}>{children}</Provider>
  }
  return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) }
} 

It seems like there’s an object being passed as an argument and then it’s assigned to nothing? Trying to figure out what the {…properties} = {} syntax means in the function declaration.

Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems like there’s an object being passed as an argument and then it’s assigned to nothing?

I assume you’re referring to the = {} at the end of (and at the start of):

 {
    preloadedState = {},
    // Automatically create a store instance if no store was passed in
    store = setupStore(preloadedState),
    ...renderOptions
  } = {}

That’s default argument value syntax. To show a simpler example, if I had a paintCar function, and I wanted to default my car to an empty object if none is provided, I could do:

function paintCar(paintColor, car = {}) {
    car.color = paintColor;
    return car;
}

// this works, even though I didn't provide a car:
const redCar = paintCar('red'); // { color: 'red' }
// ... because JS defaults that argument to "{}"

For any argument, to any function, you can add a = something to make it default to that something. The only requirement is that all the defaults have to come last, so you can’t do (say):

function fake(foo=1, bar){

(or technically you can, but when you do fake(someBar) it will get counted as the foo argument, not the bar argument)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading