0

I have some simple code:

 context.drawImage(image, 0, 0);

I was wondering if it would be possible, using something like ES6 spread (edit: spread syntax, not 'spread operator') features, to eliminate the magic numbers and make the code more explicit:

 const TOP_LEFT = [0, 0]
 context.drawImage(image, ...[TOP_LEFT]);

Is there a way I can use a variable as multiple arguments in a function call?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494

1 Answers1

2

Yes — exactly the way you did, but without [] around it when you use it:

context.drawImage(image, ...TOP_LEFT);

Live Example:

function drawImage(image, x, y) {
  console.log("image = " + image);
  console.log("x = " + x);
  console.log("y = " + y);
}

const TOP_LEFT = [0, 0]
drawImage("the image", ...[TOP_LEFT]);

Now, you might not want to do that in a tight loop of thousands of iterations, because in theory and as specified, ...TOP_LEFT involves calling a function on the array to create an iterator object, and then repeatedly calling a method on that iterator which creates a result object each time, and getting a property from that result object. But all of that is potentially subject to optimization, and in any case, we generally want to avoid worrying about performance until/unless there's a specific performance problem to address.

You might help the optimizer by freezing your array:

const TOP_LEFT = Object.freeze([0, 0]);

...but you'd want to test your target environments to see if that's actually useful.


Side note: ... isn't an operator, and couldn't be. An operator, like a function, has a single result value. Spread (and rest) are primary syntax, not operators, like for statements, function declarations, and object initializers.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This works perfectly - I'll accept it when the timer runs out. I don't know who the downvoter is, that's very rude for them downvote without providing any feedback. – mikemaccana Jun 29 '18 at 11:37
  • @mikemaccana - Glad that helped. In general, it's perfectly fine to downvote without leaving a comment, and *explaining* downvotes is discouraged by Stack Exchange. But leaving a comment saying what you think is wrong, without actively saying "I downvoted because..." can be useful. Whenever someone downvotes my answer, the first thing I do is say "Oh dear, where have I messed up?" and double-check things. So even without a comment, often useful. But when I know the answer is correct, I do sometimes ask for clarification... – T.J. Crowder Jun 29 '18 at 11:40
  • @Nick I searched for duplicates before I asked and couldn't find anything. Where are they? You haven't marked it as a duplicate either. – mikemaccana Jun 29 '18 at 11:45