1

I noticed that I can add a key value pair to an array (not an object, an array).

var a = [];       // create the array
a[0] = "test";    // conventionally setting an index of 0 to a value
a["foo"] = "bar"; // this actually sets a "key" of the array to "bar"

If I try to get the value of a.foo or `a["foo"], I simply get "bar". No errors raised.

I know that a Javascript Array is actually an object, but with special rules, but it feels weird that this doesn't throw an error.

I'm using the latest version of Chrome.

Is there an actual use case where this is ok to do? What is common practice around this fact?

1
  • 2
    You can add props to any object, like array or even function. It's not a bug. Commented Dec 3, 2017 at 19:35

1 Answer 1

2

Now try this:

> Object.getOwnPropertyNames(a)
[ '0', 'length', 'foo' ]
> a.length
1

Welcome to JavaScript! It's such a wonderful place...

Yes, you can create named properties on an array. No, you probably shouldn't. They won't be counted in Array.length, and most developers who read your code will be experiencing a moment of confusion that is unlikely to lead to a positive outcome.

If you need a named property, use a (non-array) object.

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

2 Comments

Thanks, I like the example of length, makes it clear that it is probably not a good idea. However, I'd think it's ok to use in cases where you know what you're doing, and other options aren't optimal either?
I would think those occasions would be very rare, but sure. I guess you have to ask yourself, "will I still understand this code when I come back to it six months later?" :)

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.