Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the drawbacks of setting string properties on arrays?

Tags:

javascript

I want to set string properties on my array.

E.g.

function readInput (arr) {
  var data = db.query('something');
  arr.itemType = data.itemType; // -> This
  arr.push.apply(arr, data.list);
}

var myArr = [];
readInput(myArr);

The idea is to store some meta-data on the array itself.

Is this a good approach? Am I creating any problems by doing this?

like image 878
Sachin Hosmani Avatar asked Jul 14 '14 05:07

Sachin Hosmani


1 Answers

I agree with meagar's comment above.

It doesn't make sense to add unexpected properties to the existing data structure. For example, cloning the array ignores any invalid properties of the original array and the "meta data" is not preserved:

var arr = [1, 2, 3, 4],
    newArr = [];

arr.metaSomething = "uhoh!";

newArr = arr.slice(0);

newArr.metaSomething; // undefined

Because this is an unexpected behavior (as in, it's probably not what you would like to happen), it would probably be better to store the information in an object, since that's what you are treating the array like anyway.

like image 79
Dave Avatar answered Oct 14 '22 12:10

Dave