Sobes.tech
Junior

How to set your properties for an array?

sobes.tech AI

Answer from AI

In JavaScript, arrays are objects, so you can add your own properties to them just like to regular objects.

Example:

const arr = [1, 2, 3];
arr.myProperty = 'Hello';
console.log(arr.myProperty); // Outputs: Hello

However, such properties do not affect the length of the array and are not considered when iterating with methods that work with array elements (e.g., forEach, map). They are only accessible as regular object properties.

If you need to add properties that influence the array's behavior, you can use classes and inheritance:

class MyArray extends Array {
  constructor(...args) {
    super(...args);
    this.customProperty = 'Custom';
  }
}

const arr = new MyArray(1, 2, 3);
console.log(arr.customProperty); // Custom

Thus, to assign your own properties, simply assign them to the array as you would to object properties.