2

I know that we can add properties to an already defined array like this,

var array1 = [1, 2, 3];

array1.prop1 = 'first';
console.log(array1);  // [ 1, 2, 3, prop1: 'first' ]

My question is that is there any syntax for doing the same thing while declaring the array? Something similar to this,

var array1 = [1, 2, 3, prop1: 'first']  // SyntaxError: Unexpected token :

P.S. Some may say adding properties to arrays is not considered a good practice. That is actually not the answer I'm looking for. I'm just asking about the possibility of doing something like this.

Saeed Ahadian
  • 212
  • 2
  • 4
  • 14
  • 1
    Note that "extra" properties on array objects are fine, but if you serialize the array with `JSON.stringify()` they won't be included in the result. – Pointy Dec 04 '19 at 13:55
  • 1
    And no, there's no initializer syntax for that. – Pointy Dec 04 '19 at 13:55
  • https://stackoverflow.com/a/9526896/476 – deceze Dec 04 '19 at 13:56
  • Note that the output of console.log() will only contain the property on Chrome. All other browsers will only show the actual contents of the array. – NineBerry Dec 04 '19 at 14:03

1 Answers1

3

You could take an object and assign this to an array.

var array1 = Object.assign([], { 0: 1, 1: 2, 2: 3, prop1: 'first' });

console.log(array1);
console.log(array1.prop1);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392