swiftie
swiftie

Reputation: 41

Trying to understand Javascript code that looks like object functioning as map

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);

Upvotes: 2

Views: 131

Answers (3)

Nick Parsons
Nick Parsons

Reputation: 50759

  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.)

Upvotes: 7

Udochukwu Enwerem
Udochukwu Enwerem

Reputation: 2823

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.

Upvotes: 2

symlink
symlink

Reputation: 12209

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);

Upvotes: 1

Related Questions