1

i have an object that needs to be passed to the method. most often this object will be the same but sometimes should change to the value that the calling method provides

consider i have the method called_method

called_method  = ()  => {
    const output = {
        key1: "value1";
    }
    return output;
}

If the method is called like below

called_method(); 

it should take the output value like in the method

but if it is called something like const output2 = { key2: "value2", } called_method(output2);

then it should consider returning output2. how can i do it?

we have defaulting argument in method to some value. how can i do the ssame with objects. thanks

someuser2491
  • 1,848
  • 5
  • 27
  • 63

2 Answers2

3

Use the default arguments for function like -

function called_method(output = {key1: 'value1'}) {
  return output;
}

console.log(called_method());                  // outputs - {key1: 'value1'}
console.log(called_method({key: 'newvalue'})); // outputs - {key: 'newvalue'}

But if your default argument is a large object, then store it outside the function, like this..

const defaultOutput = {
  key1: 'value1',
  key2: 'value2'
};

function called_method(output) {
  if(output) return output;
  return defaultOutput;
}

console.log(called_method());                  // outputs - {key1: 'value1'}
console.log(called_method({key: 'newvalue'})); // outputs - {key: 'newvalue'}
Karan
  • 12,059
  • 3
  • 24
  • 40
Satnam Singh
  • 324
  • 2
  • 12
  • `function called_method(output = defaultOutput) { return output; }` would work just as well. However, when you suggest creating the object outside of the function, you should add a disclaimer about what the difference is. – Bergi May 08 '20 at 12:47
3

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

called_method  = (output = {  key1: "value1" })  => {
    return output;
};

console.log("Default parameter value"); 
console.log(called_method()); 

const output2 = { key2: "value2" };
console.log("Paramter value passed in parameter"); 
console.log(called_method(output2)); 
Karan
  • 12,059
  • 3
  • 24
  • 40