Search code examples
javascriptobservablehq

Is it possible to use the for...of syntax for a for loop in observablehq?


In regular JavaScript, one can write a for loop using the for...of syntax. Is this possible with observablehq?

const array1 = [1, 2, 3];

for (const element of array1) {
  console.log(element);
}

Solution

  • You can do it in a single cell like so:

    array1 = {
      const array = [1, 2, 3];
    
      for (const element of array) {
        console.log(element);
      }
    
      return array;
    }
    

    For any JavaScript syntax, all you have to do is wrap it in curly braces {…} (to make a block statement).

    Then, if you want to expose this value to other cells in your notebook, give that cell a name by adding name = before the open curly brace, and return the desired value.

    The other syntax you use is known as an expression cell:

    array1 = [1, 2, 3]
    

    It’s just shorthand for the equivalent block cell:

    array1 = {
      return [1, 2, 3];
    }
    

    So depending how much code you want to put in the cell, you can either use an expression or a block (by adding curlies). But either way a cell can only have one name and one value.