0

If we have an empty array in JavaScript then add a property to it, the property does seem to exist but the array has 0 length.

var arr = [];
arr.property = '1234';

console.log(arr); // []
console.log(arr.property); // "1234"

In NodeJs its slightly different

console.log(arr); // [ property: '1234' ]

Is this a valid condition for an array to be in?

I spotted this whilst reading the unit tests for the JS App I work in and wonder if the test is correct to check for this kind of thing.

Edit: My query was around whether or not its a valid condition rather than why the length isn't increased. I guess it is valid if it refers to the state of it in the spec.

Asta
  • 1,489
  • 12
  • 23
  • 2
    Check the length in Node. This is just the way the console prints the array object in different environments. The array still has no length. – elclanrs May 01 '15 at 10:12
  • 1
    You're just adding a property to the array object, not an indexed element to the array. – Bergi May 01 '15 at 10:14
  • 1
    Related: [Why doesn't the length of the array change when I add a new property?](http://stackoverflow.com/a/29934626/1903116) – thefourtheye May 01 '15 at 10:14
  • NodeJS length is 0 but my query was around the validity of actually adding a property to an array. I'm wondering if our API should be changed for example. – Asta May 01 '15 at 10:27

0 Answers0