0

I've got a problem with default parameters in Javascript. I have a function like this:

function search(filterOptions = {
    foo: 'bar',
    foo2: 'bar2'
}) {
  ...
}

When I call search() without arguments, filterOptions is set to {foo: 'bar', foo2: 'bar'}, but when I call search({ foo: 'something' }), foo2 is undefined.

I cannot separate filterOptions into several arguments because options are independent.

How can i make foo2 take its default value anyway (and cleanly)?

(I'm on nodejs)

Thank you!

1
  • Your parameter is filterOptions and not foo2. Add a validation step like if(!filterOptions.foo2) filterOptions.foo2 = '' would be appropriate Commented Jan 31, 2020 at 16:13

3 Answers 3

1

You could define the defaults within the function and use the spread syntax to combine the two objects, which will override the defaults where applicable.

function search(filterOptions) {
  const defaults = { foo: 'foo', foo2: 'bar' };
  filterOptions = {...defaults,...filterOptions};
  console.log(filterOptions);
}

search({foo: 'something'});

Sign up to request clarification or add additional context in comments.

1 Comment

@RomainC I've added a link to the relevant portion of the documentation.
1

You can provide default values in the parameter list:

    function search({ foo = "bar", foo2 = "bar2"} = {}) {
      console.log("foo is " + foo + ", foo2 is " + foo2);
    }

    console.log(search());
    console.log(search({ foo: "broccoli" }));
    console.log(search({ foo: "my foo", foo2: "my foo2" }));
    

The = {} at the end is to handle the case when the function is called with no parameters.

Comments

0

You can define the default variable with an if statement:

function search(arr) {
    if(arr.bar === undefined) {
      arr.bar = "bar1";
    }
    //do whatever
}

The use of === is to make sure that the if does not run if bar is set to "undefined" (a string).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.