0

let fruit=["apple", "banana", "cherry"]

fruit.price=1000;

console.log(fruit)           // (3) ["apple", "banana", "cherry"]
console.log(fruit.price)     // 1000

I don't know why fruit.price=1000; this code run without error. Please... explain easy way please Thank you for reading. Any help would be more appreciated.

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    This is because Javascript is very flexible, and everything in it is an object. JS won't complain if you create a new property and you attach it to an array. – Jeremy Thille Mar 04 '21 at 14:36
  • 2
    Read here: https://stackoverflow.com/questions/9952126/add-property-to-javascript-array – Mario Vernari Mar 04 '21 at 14:36
  • 2
    Your comment it wrong, logging `fruit` will return `(3) ["apple", "banana", "cherry", price: 1000]` – Roberto Zvjerković Mar 04 '21 at 14:38
  • @RobertoZvjerković FF gives exactly the same result as OP has commented. `price` is there, but outside of the indexed properties. – Teemu Mar 04 '21 at 14:49
  • Does this answer your question? [Add property to javascript array](https://stackoverflow.com/questions/9952126/add-property-to-javascript-array) – 0stone0 Mar 04 '21 at 15:14

1 Answers1

0

Because JS arrays are actually objects, and you can do with array everything you can with the object, including adding and removing of properties:

const a = [1,2,3];
a.prop = 'test';
delete a[1];
console.log(a);       // [1, undefined, 3]
console.log(a.prop);  // 'test'
peter
  • 583
  • 2
  • 11
  • 2
    It's notable, that `delete` operator should not be used to delete indexed properties of the array. `delete` operator doesn't remove the slot from the array, and the length of the array remains untouched, which most likely is an unexpected result when "deleting" an index from an array. – Teemu Mar 04 '21 at 15:14
  • Absolutely! I've edited the answer to underline this. Thank you @Teemu – peter Mar 04 '21 at 15:17