Array splicing with coffeescript, what is _ref for?
Asked Answered
L

1

6

In the CoffeeScript docs for array splicing, what is the purpose of the trailing , _ref?

CoffeeScript:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]

Compiles to:

var numbers, _ref;
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
[].splice.apply(numbers, [3, 4].concat(_ref = [-3, -4, -5, -6])), _ref;
Lucais answered 28/7, 2012 at 11:6 Comment(0)
R
7

That's because CoffeeScript's slicing operation wants to return the slice it has just assigned, but splice() returns the removed elements instead.

So, in order to achieve this, it compiles the construct into a code fragment that first assigns the slice to a local _ref variable, then uses the comma operator to return that variable after calling splice().

Rentier answered 28/7, 2012 at 11:11 Comment(2)
+1 for link to comma operator, Douglas Crockford recommends against using it as it can lead to 'excessively tricky expressions' so I guess I just forgot about it. This may be impossible to answer but do you know the reason coffeeScript wants to return the slice it has just assigned, bearing in mind in this example, it is not used by anything...? Thanks.Lucais
@AJP, probably because it can generate the same code fragment whether or not the caller is interested in the returned value. In other words, "optimizing" _ref out in the latter case may not have been worth the additional complexity brought on the compiler.Campion

© 2022 - 2024 — McMap. All rights reserved.