observablehq / stdlib

The Observable standard library.
https://observablehq.com/@observablehq/standard-library
ISC License
967 stars 83 forks source link

Binding to Object Literal problem #67

Closed tomlarkworthy closed 6 years ago

tomlarkworthy commented 6 years ago

In a single cell, I wanted to create a coord, but it keeps saying syntax error near the second ":"

coord = {a:1, b:2}

To workaround I used

coord = new Object ({a:4, b:5})
tmcw commented 6 years ago

Hey Tom,

Sure, the way to do this is:

coord = ({a:1, b:2})

The () make it clear that you want to make the value an object. Another way to think about this (that will make the distinction clear) is to picture the value as the body of an arrow function:

let fn = () => { a: 1, b: 2 };

JavaScript will treat this as a label (a: 1) and then a , continuation, and then another label, which is invalid. To fix this arrow function in vanilla JavaScript, you parenthesize the body, which is the same as what you can do in Observable.

tomlarkworthy commented 6 years ago

OK thanks for the succinct expression. That's much better.

coord = {a: 1, b:2}, its a totally legit JS expression with no parenthesis necessary though. So I guess there is some dragons somewhere explaining why a cell can't always act like a JS expression. Its a surprising gotcha.

mbostock commented 6 years ago

@tomlarkworthy The syntax is covered here:

https://beta.observablehq.com/@mbostock/introduction-to-code

As Tom said, cells are not limited JavaScript expressions, so disambiguation is necessary. We should publish the grammar, but it’s something like this:

Cell :
  ImportCell
  NamedCell
  Block
  Expression

NamedCell :
  CellIdentifier = Block
  CellIdentifier = Expression
  FunctionExpression
  ClassExpression

CellIdentifier :
  Identifier
  viewof Identifier
  mutable Identifier

ImportCell :
  import NamedImports from ModuleSpecifier
  import NamedImports with NamedImports from ModuleSpecifier

https://beta.observablehq.com/@mbostock/observable-grammar

tomlarkworthy commented 6 years ago

Oh yeah "If you want to define a cell as an object literal, you must wrap the literal in parenthesis to disambiguate it from a block:"

doh, I actually even looked at that page but did not notice. Thanks!

BTW, I am really loving this software