Search code examples
javascriptobservablehq

For Loops and Logging Counters in Observable Notebooks


I am trying to loop through an array, and print a counter number for every object in that array. I am starting with the following logic:

{for (let i = 0; i < 10; i++){
   print(i)}
}

In Observable Notebooks (observablehq), this returns "undefined". So, I don't get any print statements. I am hoping to transfer this logic to loop through objects in an array, and count each object. But, I'm stuck with simply trying to use a counter!

I've also tried this:

import {log} from '@sorig/console-log-without-leaving-your-notebook'

{for (let i = 0; i < 10; i++){
   console.log(i)}
}

This also returns 'undefined'.


Solution

  • console.log works fine inside Observable. I'm not sure if was a typo, but print(i) is not a javascript method, did you mean console.log? if you try the below snippet and open developer tools you will see lines printed.

    unamedcell = {
      for (let i = 0; i < 10; i++){
        console.log(i);
      }
    }
    

    However, remember that inside Observable you have a different flavor of javascript.

    Observable’s not JavaScript

    It returns undefined because you're not naming the cells.

    If I understand your needs, looping through an array of objects there. First name a cell with you data, you could also fetch from somewhere else. Then another cell using that data Here is a fictitious case :

    data = {
      // your data
      const myObjects = [
        { a: 10, b: 20 },
        { a: 1, b: 2 },
        { a: 1, b: 5 },
        { a: 2, b: 10 }
      ];
      return myObjects;
    }
    // data = Array(4) [Object, Object, Object, Object]
    

    then another cell

    dataExample = {
      let asum = 0;
      let bsum = 0;
      for (let i = 0; i < data.length; i++) {
        asum += data[i].a;
        bsum += data[i].b;
      }
      return { asum, bsum };
    }
    // dataExample = Object {asum: 14, bsum: 37}
    

    More info on their user manual