Framework: Assigning the result of a block to a variable

I am converting one of my Observable notebooks into a document in an Observable Framework site.

I often use this pattern in my notebooks:

myData = {
  const data = [];
  for (let i = 0; i < 100; i++) {
    data[i] = i * 2;
  }
  return data;
}

But I am not sure how to translate this into an equivalent Framework document. Doing the following is not valid Javascript and doesn’t work in Framework.

const myData = {
  const data = [];
  for (let i = 0; i < 100; i++) {
    data[i] = i * 2;
  }
  return data;
}

I get the following error

SyntaxError: Unexpected keyword 'const'

I can’t see this pattern addressed in the Framework documentation. Is there a recommended way of implementing it?

Here are two approaches. The first one is a block that creates and populates the array directly. Its value is usable outside the block only after the block has run, so an external code that consumes data never sees it empty:

const data = [];
for (let i = 0; i < 100; i++) {
  data[i] = i * 2;
}

Alternatively, use an IIFE. It is a bit overkill for this example, but might be useful for more complex functions that use “internal” variables that you want to keep in a hidden scope (and expose a single result):

const data = (() => {
  const data = [];
  for (let i = 0; i < 100; i++) {
    data[i] = i * 2;
  }
  return data;
})();
2 Likes

Thank you @Fil, this is very helpful. Both approaches work in my case.

1 Like