I am reading through Eloquent Javascript and I had a question regarding this passage and the usage of curly braces:
This means that curly braces have two meanings in JavaScript. At the start of a statement, they start a block of statements. In any other position, they describe an object. Fortunately, it is almost never useful to start a statement with a curly-brace object, and in typical programs, there is no ambiguity between these two uses.
and this passage:
Values of the type object are arbitrary collections of properties, and we can add or remove these properties as we please. One way to create an object is by using a curly brace notation.
var journal = [
{events: ["work", "touched tree", "pizza",
"running", "television"],
squirrel: false},
{events: ["work", "ice cream", "cauliflower",
"lasagna", "touched tree", "brushed teeth"],
squirrel: false},
{events: ["weekend", "cycling", "break",
"peanuts", "beer"],
squirrel: true},
/* and so on... */
];
The above code looks like a bunch of properties and their array values. What are the brackets doing? They seem to be grouping each property as an array value and a boolean. Is that what the curly brackets are doing? According to the definition, are they starting a block of statements or are they describing an object? What does it mean to describe an object with curly brackets? Is an object in javascript just a collection of properties where 1 is sufficient to make it an object?
There's only one statement in the code you posted: the declaration of and assignment to journal
. It is being initialized to an array of objects, each of which has two properties: events
and squirrel
. Assuming that the "and so on" continues the pattern, each events
property is initialized to an array of string values and each squirrel
property is being initialized to a boolean.
Each pair of (square) brackets defines an array and each pair of curly brackets (braces) define objects. That's what's going on.
As to your question "What does it mean to describe an object with curly brackets?", this is described in the documentation of JavaScript object literals.