8

Going through the Eloquent Javascript book where I encountered something I haven't seen before.

In the code snippet below the variable 'map' is followed by empty curly braces. Can someone please explain what this means? Does this do anything tot he function that follows.

Also, can someone explain what map[event] = phi; does exactly? I take it this map refers to the variable 'map' we declared in the first line...

var map = {};
function storePhi (event, phi) {
  map[event] = phi;
}

storePhi("pizza", 0.069);
Ronny Blom
  • 149
  • 2
  • 6
  • `map = {}` is declaring an object. `map[event] = phi` is adding a property to `map` where the name is equal to the value of `event` and `phi` is the associated value. – Mike Cluck Jun 24 '16 at 16:24
  • 3
    Possible duplicate of [JavaScript arrays braces vs brackets](http://stackoverflow.com/questions/5129544/javascript-arrays-braces-vs-brackets) – Adam Buchanan Smith Jun 24 '16 at 16:24
  • 2
    What have you tried? Have you done even basic research? A quick google search for "curly braces in Javascript" answers your question... – Luke Taylor Jun 24 '16 at 16:25
  • I did indeed do research Luke Taylor. I hadn't yet seen an empty object being declared. I was probably overthinking the significance of it. I now see that this specific example shows that the object is 'filled' in the next steps. – Ronny Blom Jun 24 '16 at 16:39

2 Answers2

14

The {} represents an empty object.

map[event] = phi will add (or overwrite) a property on the map object with the name event and assign it to a value of phi. This way, you can do map.EVENT_NAME to get the value of phi for that event.

After performing storePhi("pizza", 0.069);, map will look like this:

console.log(map);
map = {
  pizza: 0.069
}

console.log(map.pizza);
map.pizza = 0.069
jeffjenx
  • 17,041
  • 6
  • 57
  • 99
  • 1
    That's a great explanation for what turns out to be a really simple concept. I now understand that the empty object is 'filled' by storePhi() and how the properties and their value are created! – Ronny Blom Jun 24 '16 at 16:55
  • 1
    Cool. It might also be worth mentioning that `map.pizza` and `map["pizza"]` are two ways to say the same thing. – jeffjenx Jun 24 '16 at 17:54
2

It means the variable is a dictionary that stores key value pairs. The subscript or the value within the [] brackets is the key and the value on the right side is the value.

Venkat
  • 1,095
  • 2
  • 13
  • 25