Home > Mobile >  What does these in a JavaScript function parameter `{ environment = 'test' } = {}` mean?
What does these in a JavaScript function parameter `{ environment = 'test' } = {}` mean?

Time:09-29

Can anyone please help out on these questions, It is more syntactically driven Below includes the code;

const makeServer = ({ environment = 'test' } = {}) => {}

I got this from a tutorial and all I could see here is setting up the default parameter to the function makeServer, I wanted to know that since we have an object as the function parameter, then why do we need to re-assign, another object to it?

CodePudding user response:

They want to destructure the argument to the function and give a default parameter if none is provided.

If you don't pass a default argument for the function param you'll get a runtime error when calling a function with no param (or undefined).

const makeServer = ({ environment =  'test' }) => {}
makeServer();

will lead to something similar to this

Uncaught TypeError: Cannot read properties of undefined (reading 'environment')

CodePudding user response:

You are not re-assigning an empty object to it, you are defining a default value to use in case the function is being explicitly called with an empty object.

enter image description here

  • Related