0

I saw this for the first time (or noticed it for the first time) today during a maintenance of a colleagues code.

Essentially the "weird" part is the same as if you try to run this code:

var arr = [];
arr[0] = "cat"; // this adds to the array
arr[1] = "mouse"; // this adds to the array
arr.length; // returns 2

arr["favoriteFood"] = "pizza"; // this DOES NOT add to the array. Setting a string parameter adds to the underlying object
arr.length; // returns 2, not 3

Got this example from nfiredly.com

I don't know what the technical term for this "case" is so I haven't been able to find any additional information about it here or on Google but it strikes me very peculiar that this "behaviour" can at all exists in JavaScript; a kind of "mix" between Arrays and Objects (or Associative Arrays).

It states in the above code snippet that that Setting a string parameter adds to the underlying object and thus not affect the length of the "array" itself.

What is this kind of pattern?
Why is it at all possible? Is it a weird JS quirk or is it deliberate?
For what purpose would you "mix" these types?

1
  • A relevant lightning talk from 2012: Wat Commented Mar 8, 2016 at 19:10

2 Answers 2

2

It's possible because arrays are objects with some special behaviors, but objects nevertheless.

15.4 Array Objects

However, if you start using non-array properties on an array, some implementations may change the underlying data structure to a hash. Then array operations might be slower.

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

Comments

2

In JavaScript, arrays, functions and objects are all objects. Arrays are objects created with Array constructor function.

E.g.

var a = new Array();

Or, using shortcut array literal,

var a = [];

Both are the same. They both create objects. However, special kind of object. It has a length property and numeric properties with corresponding values which are the array elements.

This object (array) has methods like push, pop etc. which you can use to manipulate the object.

When you add a non-numeric property to this array object, you do not affect its length. But, you do add a new property to the object.

So, if you have

var a = [1];

a.x = 'y';

console.log(Object.keys(a)); // outputs ["0", "x"]
console.log(a); // outputs [1];

Comments

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.