0

I defined an array like

let a = [4,5,6]

then I attached a property to a like

a.stuff = 'hi'

For some reason, there is no error and if I stringify in html tags it doesn't show the stuff property but it does show in the browser console.

What kind of data type is it now? An array or some kind of hybrid? Is it good practice to do things this way? Why doesn't the stuff property show in html tags?

ima_prog
  • 119
  • 1
  • 9
  • 1
    JS array is an object – Nikita Mazur Sep 28 '21 at 13:02
  • @NikitaMazur does that mean the array has an undefined key name after I set the stuff property? – ima_prog Sep 28 '21 at 13:03
  • [JavaScript's treatment of objects may be different than what you've experienced in other languages](https://stackoverflow.com/questions/9108925/how-is-almost-everything-in-javascript-an-object). Many items that are not a "plain object" can still be given properties like a dictionary. That said, if you need a dictionary, just use a plain object to keep it idiomatic. – Alexander Nied Sep 28 '21 at 14:09

5 Answers5

0

Arrays are objects theirselves, once you added a property to it, it becomes an object with named property.

rajabraza
  • 333
  • 3
  • 11
0

The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

let a = [4,5,6]

a.stuff = 'hi'

for (let el of a) {
  console.log(el);
}
Andy
  • 61,948
  • 13
  • 68
  • 95
0

You can always find it out yourself using the typeof operator which you can find right here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof . But in general JS arrays are considered object. And an object as well after trying to attach a property to it.

botana_dev
  • 418
  • 4
  • 16
0

It's kind of both Array and Object. This can be seen by simply using the console:

console.log(a)
[4, 5, 6, stuff: 'hi']
0: 4
1: 5
2: 6
stuff: "hi"
length: 3
[[Prototype]]: Array(0)

console.log(a instanceof Array)
true
console.log(a instanceof Object)
true

Note that in JavaScript an Array is an Object (check this article).

cj-2307
  • 259
  • 3
  • 14
0

It is always an 'object'.

let a = [4,5,6]
console.log('a:', a)  // a: [4,5,6]
console.log('typeof a: ', typeof a); //  typeof a:  object

a.stuff = 'hi';
console.log('a:', a)  // a: [4, 5, 6]
console.log('typeof a: ', typeof a); //  typeof a:  object
Yana Trifonova
  • 586
  • 7
  • 28