Object Literals with quoted properties raise Syntax Errors

I would say this is a bug but there’s no ‘bug’ option. I hope this is the best place to put this.

The screenshot should be self-explaining:

it’s totally correct in javascript to quote properties in an object literal, but in the observable notebook i get a Syntax Error…

The syntax error is because a naked {} expression is seen as a function block not an object. Just surround it with parens:

15

2 Likes

To elaborate slightly, there are two syntax issues here.

The first is that cells are either expressions or block statements (not programs), so if you want to define two object literals in the same cell, you have to put them both in a block statement:

{
  const object1 = {a: "a"};
  const object2 = {"a": "a"};
}

The second issue is that, if you use the expression form of a cell, you need to wrap object literals with parentheses, as @Fil mentioned.

The way to think about cells is that they are like bodies of arrow functions. So, if you want to write an arrow function that returns an object, you’d say:

() => ({a: "a"})

And similarly if you want to write an arrow function that defines two object literals, you’d say:

() => {
  const object1 = {a: "a"};
  const object2 = {"a": "a"};
}

Now just drop the () => and you have an Observable cell. This is discussed further in Introduction to Code.

1 Like