1

I'm doing a lot of stuff with D3, so I've got lots of arrays of values, and to make code clearer, rather than placing the value arrays within another object with meta-information (like name, color, whatever) I'm just setting that meta-information as properties on the array. It makes the code a lot clearer, and easier to do d3 operations / other stuff to related data.

Is there anything that's going to hurt me down the line? Object.keys isn't going to work right, and the code is going to be slightly harder to look at in the console, but I can work around that.

Code example:

rather than

var a = {
    name = "something",
    foo  = "bar"
    values = [{x: 1, y:2}, , , ]
};

doing

var a = [{x:1, y:2}, , , , ];
a.name = "something";
a.foo  = "bar"
  • I'll let someone more experienced chime in with a more rigorous answer, but I think that if it makes for clearer code, and a better workflow, I'd be willing to tolerate a slight impact to performance, although I don't think that should be an issue for you! – Cameron Hurd Feb 26 '14 at 17:29
  • Here's a good answer to read up on for the performance component of the question: http://stackoverflow.com/questions/8423493/what-is-the-performance-of-objects-arrays-in-javascript-specifically-for-googl – Cameron Hurd Feb 26 '14 at 17:30
  • I have seen a video on youtube stating that in your second snippet the compiler is less able to optimize the code. I have not found the video yet but it was something with chrome game performance and posted within the last 10 months. – surfmuggle Feb 26 '14 at 19:07

1 Answers1

1

When writing code, I like to follow the principle of "least surprise". I would be a little surprised to see custom attributes added to an array since I wouldn't really expect it. You have to ask yourself: "Do those attributes really belong on the array?". I think the answer is "No". The data you have are just along for the ride with the array. Hence I like the declarative approach you have:

var data = {
    name = "something",
    foo  = "bar"
    values = [{x: 1, y:2}]
}

This is far easier to read and it makes more sense when you do something like data.name, data.foo, and data.values. The access to your data is pretty uniform in this case. However, if you were to use the other approach, you would be accessing data.foo and data.name, but data itself for the values. I don't expect an array to have additional properties so while I would understand the code, it's an added bit of cognitive load I don't really need.

So from the perspective of someone who is reading the code (which includes you!) and with future-maintenance and understanding in mind, I would go with the first option.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295