8

The Confusing discussion

In this question, there is a discussion on the concepts of associated array and object in javaScript which I got a bit confused.

In this example code:

var check = {
  pattern : {
    name: /^[a-zA-Z-\s]{1,20}$/,
    email: /^[a-zA-Z0-9._(-)]+@[a-zA-Z0-9.(-)]+\.[a-zA-Z]{1,4}$/,
    pass: /.{6,40}/,
    url:  /^[(-)\w&:\/\.=\?,#+]{1,}$/,
    aml:  /<(.+)_([a-z]){1}>$/
    }
};

Here is the discussion makes me confused:

@steven.yang the outer object is not an associative array in your sample, but that is what is being asked for

@sissonb what do you mean by 'outer object is not an associative array'? I think associated array is expressed as object in javascript. The difference is in the notation - either through foo.bar or foo[bar]

@steven.yang associated array means key => value. http://en.wikipedia.org/wiki/Associative_array Your inner object has a key of pattern, the object containing this associative array has no key.

My Understanding of Associated Array and Objects in JS

Associated array is defined as key-value pairs which is expressed as the object in JavaScript.

The outer object assigned to check has a key pattern and an value of another object. The inner object has keys of name, email ... and corresponding values of regular expression objects.

Could both objects be counted as associative arrays?

Community
  • 1
  • 1
steveyang
  • 9,178
  • 8
  • 54
  • 80

5 Answers5

7

Not really, here's why:

var arr = new Array();
arr["foo"] = 100;
arr["bar"] = 200;
console.log(arr.length); // Prints 0.

Adding elements to an associative array should increase its length (IMO).

It looks and acts (somewhat) like an associative array because of syntactic sugar. What appear to be "array entries", however, are (just) object properties.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • `.length` has nothing to do with it – Raynos Nov 16 '11 at 03:02
  • @Raynos I disagree. Arrays have length/size, associative or not. – Dave Newton Nov 16 '11 at 03:03
  • 1
    find me a definition of associative array which states they must have a length – Raynos Nov 16 '11 at 03:05
  • @Raynos Find me one where adding an element to it doesn't increase its size. – Dave Newton Nov 16 '11 at 03:06
  • 2
    the wikipedia article has no mention of size or length – Raynos Nov 16 '11 at 03:08
  • @Raynos I can't tell if you're being sarcastic or not. I don't care what Wikipedia says w.r.t. the length of an array. An empty associative array shouldn't have anything to iterate over. – Dave Newton Nov 16 '11 at 03:12
  • @Dave - have you ever used arrays in C? They don't have a length property. Of course adding an element to an array increases its size, but that doesn't mean the language has to actually provide a "size" or "length" property. You can iterate over the properties of a JS object without needing "length". – nnnnnn Nov 16 '11 at 03:12
  • 1
    You also seem to be confusing `Array` with associative array. I think they are completely unrelated. And an empty associative array (object) does indeed have no own properties to iterate over – Raynos Nov 16 '11 at 03:13
  • @nnnnnn No, they don't--they also allow random tromping through memory. They're not associative arrays, either. And yes, you *can* iterate the properties of a JS object--but you may get more than the elements you've explicitly added, which is why `for/in` doesn't do what almost everybody *expects*. – Dave Newton Nov 16 '11 at 03:14
  • @Raynos Nope, I'm not: the same holds true for any object--I just picked one. – Dave Newton Nov 16 '11 at 03:15
  • @DaveNewton If we sensible define iteration as iterating over the own properties of an object using, say `Object.keys` then it does work. The fact that `for/in` iterates over enumerable properties of prototypes means it's not an iteration operation wrt associative arrays. ` massive tangent>` – Raynos Nov 16 '11 at 03:17
  • @Raynos Again, *I* believe the principle of least surprise applies to associative arrays, and I believe JS objects fail that test. – Dave Newton Nov 16 '11 at 03:18
  • There isn't a single last-word definition of "associative array", so it doesn't bother me that you and I have different definitions. You do mention some good points about features that are useful in associative arrays, but the "missing" features in JavaScript are easy to code if desired. The fact that JavaScript's `for/in` doesn't do what people who don't know the language expect doesn't mean that what it does do is bad. (I didn't mean to suggest that C arrays are associative: I was just giving an example of a pretty popular language that implements arrays without a "length" property.) – nnnnnn Nov 16 '11 at 03:30
  • 1
    @nnnnnn I don't care if the length is computed, or a property. C expects developer-management of array length, which is fine. It's also not OOP, so I wouldn't *expect* any data structures to have properties, other than what the developer provides. JS *is* an OOPL, so I expect structures to have meaningful properties. IMO an associative array should have a meaningful `length` property, and iteration should do what *I* expect. Again--this is just *my* opinion; doesn't mean anything in the grand scheme of things :) – Dave Newton Nov 16 '11 at 03:33
  • Cool. I think we're on the same page about it not being a problem that we're not on the same page about associative arrays. (Sorry, once I started that sentence I couldn't seem to stop it.) I respect your point of view on this as long as you keep saying "should" not "must", and like I already said you've certainly made some good points. As far as having an associative array in JavaScript that exactly meets your definition, that's easy enough to implement via your own "class" (yes, I know JS doesn't have classes) - clunkier than built-in support from the language, but do-able if needed. – nnnnnn Nov 16 '11 at 03:42
  • @nnnnnn It's Turing-complete; anything is possible ;) We could *add* associative arrays... because JavaScript clearly doesn't have them :D – Dave Newton Nov 16 '11 at 03:44
  • if one where the change `var arr = new Object()`; then you could say this is an object as an associated array – david Nov 16 '11 at 03:52
  • @david You could, but it still wouldn't meet *my* criteria for how an associative array should act. Again: it's a matter of semantics, and my version of what an associative array's semantics should be doesn't match yours. I'm okay with that. – Dave Newton Nov 16 '11 at 03:56
  • @DaveNewton By your definition a hash table is not an associative array. You may want to find a more suitable term to use here. (A hash table _is_ an associative array). It's not a matter of your criteria vs my criteria but rather a matter of using technical terminology correctly, speaking the same language and not causing confusion. – Raynos Nov 16 '11 at 04:02
  • @Raynos Think whatever you want. – Dave Newton Nov 16 '11 at 04:04
  • 1
    I checked this as a answer because of the following discussion comments which clear the confusion of associative array and objects. – steveyang Nov 17 '11 at 03:59
  • 2
    @steven.yang I think I got *more* confused ;) – Dave Newton Nov 17 '11 at 04:29
6

If you define "associative array" as a data structure that stores information as a collection of key-value pairs, then yes, JavaScript objects are associative arrays.

However, the phrase "associative array" is not generally used in the context of JavaScript, rather, we say "object". I'd suggest sticking to standard JS terminology to avoid misunderstandings.

Note that JS also has (non-associative) arrays, with elements accessed via numeric indexes. These are also objects and so allow non-numeric key properties, but this is generally considered bad practice.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • As soon as it's a non-numeric index, it's an object property, though, just like any other object. – Dave Newton Nov 16 '11 at 03:20
  • @DaveNewton numeric indexes are also object properties – Raynos Nov 16 '11 at 03:21
  • @Raynos But they're different--using numeric indices *does* increase the array size, whereas properties don't. – Dave Newton Nov 16 '11 at 03:21
  • @DaveNewton that doesn't mean they are not object properties. It simply means that `Array` does magic on the internal `[[DefineOwnProperty]]` property to make sure `length` is correct. Specifically [ES5.1 15.4.5.1 step 4](http://es5.github.com/#x15.4.5.1) where it checks whether the property is an "array index". – Raynos Nov 16 '11 at 03:24
  • @Raynos But I don't *care* about the semantics. I care about having my expectations met. JS objects do not meet *my* expectations of an associative array, so I don't consider them an associative array in a *meaningful way*. Reasonable people can disagree: we disagree, and I'm okay with that. You know my reasons--I believe they're valid, you don't. 'Nuff said. – Dave Newton Nov 16 '11 at 03:28
3

There are no associative-arrays in JavaScript. Everything is object.

Certainly they are similar but associative-arrays in JavaScript are just objects.

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
  • 3
    Why are objects not assiocative arrays? What definition of associative array do they fail – Raynos Nov 16 '11 at 03:03
  • @Raynos Iterating over the members of an associative array should return only the elements of the associative array. The same is not the case for objects and their properties. – Dave Newton Nov 16 '11 at 03:05
  • terminology...certainly you could say associativeArray = Object and Object=associativeArray in JavaScript, but in my opinion they are all just Object. – John Hartsock Nov 16 '11 at 03:05
  • @DaveNewton depends of your definition of iteration. I'd argue iterating over the own properties does exactly what you want. The fact you can iterate over non-own properties does not make it a non-associative array – Raynos Nov 16 '11 at 03:06
  • @JohnHartsock everything is both ;) – Raynos Nov 16 '11 at 03:06
  • @Raynos Again, I disagree: the principle of least surprise would also disagree. Iterating over an associative array's elements should return only explicitly added elements. That there's no (trivial) way to differentiate between those, and other properties of the underlying object, make it useless as a typical associative array. I won't argue semantics, though: I don't believe a JS object fulfills the least-surprising contract of an associative array--we'll need to agree to disagree. – Dave Newton Nov 16 '11 at 03:10
  • @DaveNewton It really depends what you expect associative arrays to be, you make a good point though. – Raynos Nov 16 '11 at 03:12
  • @Raynos Everything depends on what we expect :) I expect a new associative array to be empty, and I expect adding objects to increase length. – Dave Newton Nov 16 '11 at 03:13
  • -1 since nothing is provided to back up the claims, which others object to. – hippietrail Jan 09 '13 at 11:17
3

Associative Array

In computer science, an associative array (also called a map or a dictionary) is an abstract data type composed of a collection of (key,value) pairs, such that each possible key appears at most once in the collection.

As far as I know objects in JavaScript match that definition.

Of course there is no unique "Associative Array" object, that's any different then any other normal object. So if you want associative array functionality use a javascript object.

However the following is a common piece of misinformation

There is no associative array in JavaScript

You should simply ignore these people, maybe try to convince them they are wrong.

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • How about this? "There is no unique associative array data type in javascript that is any different than an object". If you want the behavior of an associative array in javascript, use a javascript object. – jfriend00 Nov 16 '11 at 03:26
  • Rather then a -1 can you please identify what criteria of "Associative Array" objects fail – Raynos Nov 16 '11 at 03:26
  • 2
    I'm not criticizing your post nor did I vote it down. I was just suggesting an enhancement. I think people get confused in javascript because they are expecting a data type called an "associative array" and don't realize that an object has all those capabilities. Then, they use an "array" and get further confused when `.length` remains zero even though they have added items to the array. – jfriend00 Nov 16 '11 at 03:28
  • @sissonb generally when one claims that the majority spread mis information, the majority will _continue_ to spread misinformation by downvoting my answer. And one tries to educate the JS community. [tag:sigh] – Raynos Nov 16 '11 at 03:55
  • Here's another source, http://www.tcl.tk/man/tcl/tutorial/Tcl22.html Look at this code to better understand how to iterate over objects http://jsfiddle.net/KsQur/2/ – sissonb Nov 16 '11 at 04:09
  • I'm not sure that arguing over terminology that clearly means slightly different things to different people is the most useful bit of education you could provide. – Tim Down Nov 16 '11 at 09:53
  • 1
    @TimDown meh, if people don't have a standardized definition for terminology it would be annoying. If I ask for an apple and you give me an orange, then insist that orange is an apple, I will rage. – Raynos Nov 16 '11 at 15:06
  • @Raynos Why do you insist on calling an Object an Associative Array ? because of old languages, like PHP ? that's not a good reason. (* i have upvoted your answer, anyway) – c69 Nov 18 '11 at 14:37
  • 1
    @c69 because it satisfies the definition of an associative array. – Raynos Nov 18 '11 at 15:00
  • @Raynos yes, they are synonyms, but 'Associative array' is longer and archaic. Also, its wrong to call complex trees or circular structures 'arrays' - and those are very frequently seen in daily js. Because DOM is a deep tree with circular references. – c69 Nov 20 '11 at 23:47
0

My response is coming late, but I hope this can help people to understand this difference. I was reading this post and there isn't a satisfactory definition of an associative array. JavaScript doesn't have Associative Arrays. These are just objects that you can treat as associative arrays for convenience. In objects you store values as named properties, very similar to associative arrays in other programming languages. That's why you can access the properties like an associative array, but with methods associated to objects. You can test creating an object and try all the things you can do with an associative array, but you can't do all the methods of an array.