0

I found myself coding this pattern, which seems like an abuse of javascript but also seems to work:

zoo.animals = [cat, dog, lemur]
zoo.animals.currentlySelected = zoo.animals[0]

So I'm creating an animals array, but then realizing I also want a named property of animals called currentlySelected. I guess actually I end up with an array called myapp.things and a separate object with the same name? I like that the list of animals and the knowledge of which one is currently selected are both in the zoo.animals namespace. Am I likely to be causing unforseen problems here?

n.b. : I expect people will say that the correct way to do this is

zoo.animals.listOfAll = [cat, dog, lemur]
zoo.animals.currentlySelected = zoo.animals.listOfAll[0]

but my question is more about how and why my way is wrong rather than what alternate approach is the best.

foobarbecue
  • 6,780
  • 4
  • 28
  • 54
  • 5
    As long as you don't use `for...in`, you should be fine. – user123444555621 Jun 10 '14 at 15:41
  • 3
    The real abuse here is keeping the animals in a zoo, poor things, you should rename it to `jungle.animals` to be more humane, and keeping a lemur with a cat and a dog doesn't sound very smart, there's bound to be some issues there! – adeneo Jun 10 '14 at 15:44
  • 1
    @FrédéricHamidi - I'm not taking that bet, those things are vicious little creatures, with their beady yellow eyes. – adeneo Jun 10 '14 at 15:48
  • https://i.chzbgr.com/maxW500/6923348992/h18BC9C27/ – adeneo Jun 10 '14 at 15:50
  • 1
    I think marking this as duplicate might have been premature. The author even says in their opening that it *works technically*, but is instead asking whether it's *a bad idea or not*. – cloudfeet Jun 10 '14 at 15:54
  • 1
    Seeing as this has been marked as a duplicate, I've [added an answer](http://stackoverflow.com/a/24145496/472388) on the *other* question that aims to address this one. If this gets un-marked as a duplicate, I'll happily delete that answer and repost it here. – cloudfeet Jun 10 '14 at 15:56
  • @cloudfeet, your answer over at the other question was exactly the info I was looking for, thanks! Surprised to find that this is an accepted coding pattern. I don't contest the duplication; I had missed the other question in my initial search. Too bad it's not very well-written. – foobarbecue Jun 10 '14 at 16:03
  • Yeah, it personally strikes me as a little odd - and it's also lost if you do `JSON.stringify()` or any array-slicing, etc. (I've added that to my answer). I also haven't seen it used much in the wild, which means that it might confuse other people reading your code. It's a judgement call, really... – cloudfeet Jun 10 '14 at 16:11

0 Answers0