2

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

4
  • Yes, just use a default parameter value? It doesn't care whether it evaluates to an object or someting else. Commented May 8, 2020 at 12:35
  • thanks could you provide an example. Commented May 8, 2020 at 12:35
  • 1
    It makes your question a bit confusing if the input of that function is also the output of the function. It might help if your example function actually did something. Commented May 8, 2020 at 12:36
  • Your function doesn't take an argument... Commented May 8, 2020 at 12:37

2 Answers 2

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)); 

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

Comments

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'}

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.