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.

4
  • 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. Commented Dec 4, 2019 at 13:55
  • 1
    And no, there's no initializer syntax for that. Commented Dec 4, 2019 at 13:55
  • stackoverflow.com/a/9526896/476 Commented Dec 4, 2019 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. Commented Dec 4, 2019 at 14:03

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

5 Comments

Would it be easier to read if you just spread [1,2,3]? As in { ...[1,2,3], prop1: 'first' }
@Kobe, yes, or no, because this code should never be used. it is for educational purpose only.
@deceze, please see above comment.
@NinaScholz Sure, I only mentioned it to make it easier to write, not for actual use :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.