0

In my express server I have a function that if a request body is passed to it, it destructures the properties from it as so:

export function createProxiedRequestBody({ dateRange, dateFrom, filters },
dateDefault) {
}

Its a common function where the object passed to it could be void but is obviously causing errors as such:

Cannot read property 'dateRange' of null.

Is there a fancy JavaScript way I can ignore these in the parameters rather than writing an if block statement in the function ?

1
  • Read about default values Commented Jan 17, 2019 at 13:51

2 Answers 2

1

You can use destructured parameter with default value assignment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#Destructured_parameter_with_default_value_assignment

function createProxiedRequestBody(
   { dateRange, dateFrom, filters } = {dateRange: null, dateFrom: null, filters: null},
   dateDefault) { 
       console.log('dateRange:' + dateRange);
}

createProxiedRequestBody();  // no error, dateRange === null
createProxiedRequestBody({dateRange: 2});

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

Comments

0

You can pass default value to parameter which you want to ignore

Something like below

    function foo (x, y = 10) {
        return x + y;
    }
    
    console.log("Ignore y. Sum = "+ foo(10)); //It will ignore y while calling foo function
    console.log("Without ignoring y. Sum = "+ foo(10, 20)); //It assign value to y i.e 20

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.