0

Here's a sample code that resembles my situation:

var customProcessor = function test1(arga, argb, argc, argd) {
  console.log('customProcessor', 'arga', arga);
  console.log('customProcessor', 'argb', argb);
  console.log('customProcessor', 'argc', argc);
  console.log('customProcessor', 'argd', argd);
};

var utilityMethod = function test2(arga, argb, someFunc, cbArgs) {
  console.log('utilityMethod', 'arga', arga);
  console.log('utilityMethod', 'argb', argb);
  cbArgs.unshift(argb);
  cbArgs.unshift(arga);
  someFunc.apply(this, cbArgs); // INTENT: someFunc(arga, argb, argc, argd);
};

utilityMethod('argA', 'argB', customProcessor, ['argC','argD']);

The code above manages to pass all 4 required arguments to my customProcessor method but the following lines aren't the most readable in terms of intent:

  cbArgs.unshift(argb);
  cbArgs.unshift(arga);
  someFunc.apply(this, cbArgs); // INTENT: someFunc(arga, argb, argc, argd);

Is there some way to write them in a more self-explanatory fashion ... using a JS syntax that I might not know about?

Here's what I'm imagining would be more readable:

  // not real code
  someFunc.apply(this, [arga, argb, cbArgs]);

but I need to know if there is a realistic JS syntax for accomplishing this?

2
  • 1
    [arga, argb, ...cbArgs] Commented Aug 19, 2017 at 1:49
  • @ASDFGerte - thanks! would you mind answering so i can mark it as the correct answer? Commented Aug 19, 2017 at 1:51

2 Answers 2

2

Use the spread syntax:

[arga, argb, ...cbArgs]

Note that this also works directly on the function call, replacing apply (if you do not need an explicit this), e.g. someFunc(arga, argb, ...cbArgs)

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

2 Comments

yes you are right again! both work: someFunc.apply(this, [arga, argb, ...cbArgs]); or someFunc(arga, argb, ...cbArgs);
@pulkitsinghal make sure to check both tabs in the browser support section as it's not supported in IE and some older bowsers developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
1

function customProcessor(a, b, c, d) {
  console.log('customProcessor:', a, b, c, d);
};

function utilityMethod(arga, argb, someFunc, cbArgs) {
  console.log('utilityMethod  :', arga, argb);
  someFunc(arga, argb, cbArgs[0], cbArgs[1]); 
  // or
  someFunc.apply(this, [arga, argb].concat(cbArgs)); 
};

utilityMethod('argA', 'argB', customProcessor, ['argC','argD']);

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.