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