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.