Loops in Observable

I’m new to observable and I was trying to use the for loop in my notebook but it keeps coming up as syntax error. What is the correct way to write a for loop, if it’s possible? Thank You

Hi - most likely, all you need to do is put it in a block: put a { and } at the beginning and end of the cell. Check out the second cell in the Introduction to Observable notebook, which includes a for loop.

If that doesn’t work, post the code you’re trying to write here, and we’re happy to help.

1 Like

ahh okay. Thank you so much!

is there a way to keep the for loop dynamic?
I’m trying to regularly update the dase array with new elements as i change the variable (temp). The temp variable is base on a slider.
{
var x = 0;
for (let i = 0; i <=16; i++) {
dase[i] = calculate(temp,x);
x+= .05;
}
}

Sure, something like this notebook?

The key is the cell:

{
  let dase = [];
  let x = 0;
  for (let i = 0; i <= 16; i++) {
    dase[i] = calculate(temp, x);
    x += 0.05;
  }
  return dase;
}

The array does change and is active, however the graph i have in this notebook doesn’t seem to be updating with the change in the array dase. It however, update with the current array i have in it now. Which is very verbose and I want to shorten it down.

(location is at the current[0],current[1]…)

Sure, here’s a fork that works: https://beta.observablehq.com/d/1465951e6b0975fc

The difference is that the example I posted declares dase in the cell - and the notebook does the same. Check out this notebook on mutation for the strategy behind this: the gist is that Observable’s reactive runtime wants to know when things change, and the best way to do this is by returning new values from each cell and avoiding modifying objects. So a cell like

{
  
  let x = 0;
  for (let i = 0; i <= 16; i++) {
    dase[i] = calculate(temp, x);
    x += 0.05;
  }
  return dase;
}

Mutates the dase array that is declared in another cell, whereas a cell like

dase = {
  let dase = [];
  let x = 0;
  for (let i = 0; i <= 16; i++) {
    dase[i] = calculate(temp, x);
    x += 0.05;
  }
  return dase;
}

The latter is preferable, because Observable is able to look at this cell and say:

  • This cell depends on temp, because that variable isn’t defined in the cell.
  • So whenever temp changes, run the cell again and the value of dase changes.
1 Like