What is the prescribed way to append a value to an Array in CoffeeScript? I've checked the PragProg CoffeeScript book but it only discusses creating, slicing and splicing, and iterating, but not appending.
Asked
Active
Viewed 7.1k times
3 Answers
197
Good old push
still works.
x = []
x.push 'a'

Thilo
- 257,207
- 101
- 511
- 656
-
9Author of the [PragProg book](http://pragprog.com/book/tbcoffee/coffeescript) here. +1 to Thilo's answer. I didn't want to cover the `Array` prototype methods in the book, since there's plenty of good JavaScript documentation out there already. See, for example, https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Methods_2 – Trevor Burnham Sep 13 '11 at 15:00
-
What about if we have an object, and not a character? – Gaʀʀʏ Jun 09 '14 at 04:43
-
I was expecting [`x << 'a'`](https://ruby-doc.org/core-2.3.0/Array.html#method-i-3C-3C) to work. – Chloe Sep 13 '18 at 18:44
50
Far better is to use list comprehensions.
For instance rather than this:
things = []
for x in list
things.push x.color
do this instead:
things = (x.color for x in list)

suranyami
- 908
- 7
- 9
-
23That doesn't append values from list to things. That replaces the things array entirely. I just tested it too. – ajsie Nov 21 '11 at 11:31
-
Well, sure ajsie, you're correct, it does replace it, not append. The point is, however, that usually when you are pushing, you are often doing something **quite like** an array comprehension anyway. Not in all cases, admittedly, but a lot of the time. – suranyami Feb 26 '12 at 08:32
-
3@suranyami On the contrary, I can't think of any good use for that. I'd much rather just do `things = list`, it's far more succinct. – Michael Dorst Jul 28 '13 at 05:30
-
-
@anthropomorphic Well, of course. It's a contrived example. Let's say it's something like this instead: `colors = (item.color for item in list)` – suranyami Sep 12 '14 at 04:18
-
-
Replaced link: [CoffeeScript Cookbook](http://coffeescriptcookbook.com/chapters/arrays/) describes some other options for concatenating and merging arrays. – suranyami Oct 13 '14 at 22:44
3
If you are chaining calls then you want the append to return the array rather than it's length. In this case you can use .concat([newElement])
Has to be [newElement] as concat is expecting an array like the one its concatenating to. Not efficient but looks cool in the right setting.

Paul Schooling
- 31
- 2
-
Chaining calls is more of a stylish thing you can do however, as you stated "the method not being efficient" - `concat` returns a new array constructed from the elements of array A + array B. References to objects are kept so changes to an object referenced in either array A, array B or the concat result will be reflected in the other arrays as well. – SidOfc Aug 26 '16 at 13:18