What's the difference between Map and Array?

I’m working through JS Novice to Ninja and at the end of ch4 there is a data structure in the Quiz project that looks like a nested array, with key value pairs.

In the discussion following the new code reveal (refactoring using functions) the array is referred to as a ‘map’. As far as I know there is no new Map() operator used to create this and there is apparently no literal notation for creating a map, so I’m thinking it’s just a plain old array? If someone could clear up the confusion, that would be great! :smile:

Yes, they are using key/value pairs in the array to make it act as if it were a map.

JavaScript does have a Map object, that can be used on most web browsers.
On the Map object, you can set and get named elements, and it has a range of useful built-in methods.

The jQuery JavaScript Novice to Ninja book simulates a map using the array structure, because back when that was written there wasn’t as much good support for the Map object that we have today.

Er, the book is JavaScript Novice to Ninja 2017 edition. Would I be correct in saying that you could use either? Both Map and Nested Arrays were covered but in this case it has the form of an array as it isn’t set as a map (as per the new Map() operator).

I’ve used nested arrays before and is seems to be like a dictionary used in Python. Maybe the author updated it but forgot to set it as a Map.

"The first part of this code remains the same ― we create a map of questions and answers and store it in the quiz variable."

and a bit later…

“After this, it iterates over the quiz array and invokes the ask() function for each emphasized text question.”

So that’s where the confusion came from - referring to the same structure by different terms.

Yes, either could be used. The Map object tends to be more efficient than using an Array though, as with the array you are overloading its normal behaviour, and are restricted in the names that can be used, and the types of information that can be retrieved.

Yes I agree, especially as the Map object is covered just 50 pages before that section, to me it would have made more sense to use the Map object instead of simulating it with an array.

1 Like

I read in the Prologue of the book that: “While I was halfway through writing this second edition, I read somewhere that print books about JavaScript programming are pointless because they are out of date by the time they are published.”

Hoo boy, is that ever the case.

I was reading the intro because I was looking for infomation about which older browsers that the book intends to support.
Throughout the book IE9 and occasionally IE8 are mentioned. Given that IE8 doesn’t natively support the Map object, that lends additional weight as to why they left the old Array map technique in the example.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.