[Solved] Error with Blaze reactivity in arrays

I have the following code that doesn’t update properly. It’s just generating an html table from an array of arrays of { attribute : { style : ..., class : ... } , content : ... }

<template name="rows">
  {{ log rows }} <!-- debug -->
  {{#each row in rows}}
  {{ log row }} <!-- debug -->
  <tr>
    {{#each cell in row}}
    <td {{cell.attributes}}>{{cell.content}}</td>
    {{/each}}
  </tr>
  {{/each}}
</template>

with Template.rows.helpers({ log : v => console.log(v) })

When I add columns to the left of the table, there is a mismatch between old values and new values. For instance the row displayed by the log function doesn’t correspond to the one in the rows array in the foreach.

 {{ log rows }}
 {{#each row in rows}}
  {{ log row }} <--- not the same row as rows

I don’t know how to proceed to debug or workaround.

I solved this problem and it’s a combination of javascript misusage that I document here for future reference

1. console.log is asynchronous and uses a pointer

One cannot rely on console.log to output the state of a variable at the time it’s called. The result printed in the console can be the state of the variable before, during or after the call of console.log

The proper way to print debug info is console.log(JSON.stringify(v)) which generates a string representation of the variable. That said, the calls can still arrive in an undefined order but at least they will reflect the proper state of the variable being examined.

2. Arrays with undefined values mess with reactivity

An array like this [0, 1, undefined, 4] will be seen by Blaze as [0, 1, 4] and that will mess all reactive computations. That’s actually more of a “feature” of javascript implementation of arrays as objects.