Javascript newbie help

There’s not really much “simplified” syntax in Observable. Our notebooks are just JavaScript, with a few small changes, as outlined here: https://beta.observablehq.com/@mbostock/introduction-to-code

To be explicit, the differences:

  • Each cell in Observable is either a single expression, or a single block of code (with { }) that returns or yields a value. In both cases, the body of the cell implicitly becomes the body of a function. The cell is re-evaluated (the function is called) every time one of its inputs updates.
  • The other difference is the new keywords: viewof and mutable. These both are a way to have one cell definition create two values. With viewof, you define the JS value and its HTML view at the same time. With mutable you define both the reactive and non-reactive versions of a value.

As for your question, if you write:

{
  for (let i = 0; i <= 5; i++) {
    return i;
  }
}

… as I mentioned above, it becomes the implicit function body for the cell. Imagine something like this:

var cell1 = function() {
  for (let i = 0; i <= 5; i++) {
    return i;
  }
};

In both regular JavaScript, and Observable, calling that function will always return 0. Your loop never has a chance to run more than a single step before the function returns. And as you note, yield (creating a Generator function instead, that is capable of yielding multiple values), works differently.

1 Like