2

I'm learning javascript and came across some Javascript code that looks something like the code below. It seems like carArrays object is being turned into a map just by virtue of assigning an array to carArrays[car1.year]. So I have a number of questions about this code.

  1. What javascript rules allow you to do this?

  2. I thought [] means array. If carArrays is now a map why are square brackets being used to index into it?

  3. Is my interpretation correct about carArrays becoming a map? Or is this still considered an object with keys '1999' and '2005'?

My code:

function car( make, model, year){
    this.make = make;
    this.model = model;
    this.year = year;
}

let car1 = new car('bmw', '3series', 1999);
let car2 = new car('ford', 'crownvic', 1999);
let car3 = new car('honda', 'accord', 1999);

let car4 = new car('bentley', '5', 2005);
let car5 = new car('chevy', 'silverado', 2005);
let car6 = new car('toyota', 'rav4', 2005);

let carArrays = {};
carArrays[car1.year] = [car1, car2, car3];
carArrays[car4.year] = [car4, car5, car6];

console.log(carArrays);
Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
swiftie
  • 41
  • 4
  • 2
    `I thought [] means array.` Sure, but `[]` is nowhere in the code you posted. `{}` is an object literal. `obj[someVar]` is bracket notation, see https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – CertainPerformance Jul 07 '19 at 04:25
  • 1
    The square brackets notation on an object detones that is assigning or accessing a property in the object. In this case, you're creating a new property with the same name that `car1.year` would have (i.e. 1999) and assigning the values or car1, car2, car3 inside an array. Same for the other property. – d4vsanchez Jul 07 '19 at 04:29
  • carArrays[car1.year], first value of "car1.year" would be calulated, then it would assigned as a key to object carArrays and then rght hand side expression would be evaluated and assigned to this key of object – faizan Jul 07 '19 at 04:29
  • 3
    why the negative vote?? it is a question...as I stated I'm trying to learn javascript. – swiftie Jul 07 '19 at 04:30
  • Are you confused about what `let carArrays = {};` is *actually* doing? It's not necessarily the easiest thing to pick up on if you're new to javascript. – wahwahwah Jul 07 '19 at 04:33
  • not sure. What is confusing me is it looks like carArrays is functioning as a hash map. For example i can retrieve the first array by doing this: carArrays[1999]. That looks like a hash map. But I never did carArrays = new map(). What indicated to Javascript that carArrays was supposed to be a hash map? – swiftie Jul 07 '19 at 04:43

3 Answers3

7
  1. What javascript rules allow you to do this?

carArrays is an object (as denoted by {}). This means it will have key-value pairs, where a key points to a particular value. However, you need to define what those key-value pairs will be. At the moment your object is empty, but, you can add key-value pairs to it in multiple ways:

Directly:

let carArrays = {
  "myKey": ["element1", "element2"]
}

Using dot-notation:

let carArrays = {};
carArrays.myKey = ["element1", "element2"];

... or using bracket notation:

let carArrays = {};
carArrays["myKey"] = ["element1", "element2"];

All of the above ways of adding key-value pairs do the same thing - they add a key of "myKey" to the carArrays object with a value being an array of elements (["element1", "element2"]).

The thing to note about bracket notation is that it allows you to pass a key into the object to define it, so something like so is also valid:

let carArrays = {};
let theKey = "myKey";
carArrays[theKey] = ["element1", "element2"]

So, when you do your code:

let carArrays = {};
carArrays[car1.year] = [car1, car2, car3];

... you're using bracket notation to set a key for carArrays to be that of the value stored at car1.year (ie: 1999) and its value to point to an array of car elements ([car1, car2, car3]).

  1. I thought [] means array. If carArrays is now a map why are square brackets being used to index into it?

As discussed above, it is not only used for indexing arrays, but it is also used to get/set values on objects. This is known as bracket notation. If you delve further into Javascript you'll uncover that arrays are in fact just objects, so when you use [] on an array, you're really using bracket notation again.

  1. Is my interpretation correct about carArrays becoming a map? Or is this still considered an object with keys '1999' and '2005'?

Javascript has two main ways of representing data as a key-value pair relationship. One way is using the Map class, and another way is by using an object {}. Both new Map and {} allow you to keep a data-structure which stores key-value pair relationships. In your code you're using an object ({}), not a Map. Moreover, in the past, we didn't always have the Map class in Javascript as it is only a relatively new addition (to ES6) and so, objects ({}) were mainly used instead. To see the main differences between a Map and an Object, you can take a look at this answer or this comparison from MDN.

Thus, for your code, it is still considered an object with keys '1999' and '2005' (as you are not creating a new Map() object anywhere in your code, but instead are using a regular object ({}) to store your key-value pairs.)

Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
  • OK this answer really sheds some light, mostly answers my first 2 questions. As regards the 3rd question what I mean by map is very straightforward. I mean hash map. Both in Java and Javascript (most languages I would suspect) there is a map implementation of the (hash) map data structure in some library. In Java it is HashMap or HashTable. In javascript it is `Map` I believe that does the same thing. So it looks like javascript objects are a kind of map by default in Javascript with key/value pairs. – swiftie Jul 07 '19 at 05:04
  • @swiftie Hi, I've updated my answer to help clarify your third question. Essentially a `Map` and an object `{}` are very similar in what they do (they do have their differences though) – Nick Parsons Jul 07 '19 at 05:14
  • 2
    The [Objects and maps compared](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared) section on MDN might be a good reference. – Herohtar Jul 07 '19 at 05:16
2

To answer your question directly, carArrays is not a map.

For proper definition of a map see this. Specifically, you initialize a map using an array or object whose elements are key-value pairs like this:

let myMap = new Map([[ 1, 'one' ],[ 2, 'two' ]]);

On the other hand, car1, car2, car3, car4, car5, and car6 are all objects. carArrays is an object of arrays and not an array. The code:

carArrays[car1.year] = [car1, car2, car3];

simply creates a new key or property of 1999 in carArrays and assigns this key an array containing the three objects: car1, car2, and car3

You can visualize the carArrays object like this:

{'1999': 
    [
        {
            'make':'bmw', 
            'model':'3series', 
            'year':1999
        },
        {
            'make':'ford', 
            'model':'crownvic', 
            'year':1999
        },
        {
            'make':'honda', 
            'model':'accord', 
            'year':1999
        }
    ],
 '2005':
    [
        {
            'make':'bentley', 
            'model':'5', 
            'year':2005
        },
        {
            'make':'chevy', 
            'model':'silverado', 
            'year':2005
        },
        {
            'make':'toyota', 
            'model':'rav4', 
            'year':2005
        }
    ]
}

However, objects and maps have some similarities and differences. You can also check them on the MDN site

Also look at the accepted answer here for added clarification.

Udo E.
  • 1,958
  • 1
  • 13
  • 24
1

If you run the code and see, console.log will return this:

{
  "1999": [
    {
      "make": "bmw",
      "model": "3series",
      "year": 1999
    },
    {
      "make": "ford",
      "model": "crownvic",
      "year": 1999
    },
    {
      "make": "honda",
      "model": "accord",
      "year": 1999
    }
  ],
  "2005": [
    {
      "make": "bentley",
      "model": "5",
      "year": 2005
    },
    {
      "make": "chevy",
      "model": "silverado",
      "year": 2005
    },
    {
      "make": "toyota",
      "model": "rav4",
      "year": 2005
    }
  ]
}

The curly braces represent objects, while the square brackets represent arrays. so this code:

let carArrays = {};
carArrays[car1.year] = [car1, car2, car3];
carArrays[car4.year] = [car4, car5, car6];

creates a new object, carArrays, and creates two key value pairs. The keys are years, while the values are an array of car objects.

function car( make, model, year){
    this.make = make;
    this.model = model;
    this.year = year;
}

let car1 = new car('bmw', '3series', 1999);
let car2 = new car('ford', 'crownvic', 1999);
let car3 = new car('honda', 'accord', 1999);

let car4 = new car('bentley', '5', 2005);
let car5 = new car('chevy', 'silverado', 2005);
let car6 = new car('toyota', 'rav4', 2005);

let carArrays = {};
carArrays[car1.year] = [car1, car2, car3];
carArrays[car4.year] = [car4, car5, car6];

console.log(carArrays);
symlink
  • 10,400
  • 6
  • 25
  • 47
  • This much I knew. I ran the code myself before posting. What I don't understand is what is happening. What javascript rules are allowing this. This is not intuitive behavior if you come from a Java or C++ background. carArrays looks like it is being turned into a map. Is that the case or am I mistinterpretting?? – swiftie Jul 07 '19 at 04:38
  • 1
    @swiftie That's how you assign keys to arrays and objects. `$arr["myKey"] = [];`. JavaScript doesn't have the concept of maps. – symlink Jul 07 '19 at 04:41
  • oh right....Javascript doesn't but there is `Map` class defined somewhere (JS library) that that does maps. but I see your point... the language itself doesn't have it. – swiftie Jul 07 '19 at 05:25
  • 1
    @symlink JavaScript does have an in implementation for maps. Check my answer or see (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) – Udo E. Jul 07 '19 at 05:28