Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent javascript chapter 4 Computing correlation

Tags:

javascript

I’m currently going through book Eloquent JS and I can’t understand this code below:

function tableFor(event, journal) {
  let table = [0, 0, 0, 0];
  for (let i = 0; i < journal.length; i++) {
    let entry = journal[i], index = 0;
    if (entry.events.includes(event)) index += 1;
    if (entry.squirrel) index += 2;
    table[index] += 1;
  }
  return table;
}

console.log(tableFor("pizza", JOURNAL));
// → [76, 9, 4, 1]

You can look up JOURNAL here: https://eloquentjavascript.net/code/#4

And chapter here: https://eloquentjavascript.net/04_data.html - Computing correlation

Particularly I can’t understand this line

let entry = journal[i], index = 0;

I know that we reassign every object of the journal to entry, but what index=0 does? And every other index:

index += 2;
table[index] += 1;
like image 222
Dilovar Mudinov Avatar asked Mar 06 '26 13:03

Dilovar Mudinov


2 Answers

The function first initializes that table array with four zeros. Note also that the possible values for index on each iteration of that loop are:

  • 0, if the entry does not include the "event", and does not have the "squirrel" flag set;
  • 1, if the entry does include "event" but no squirrel;
  • 2, if the entry does not include "event" but squirrel;
  • 3, if the entry both includes "event" and is a squirrel

Those four values will act as indexes into the table. Each iteration of the loop adds one to one of the four table cells, so when the loop is finished the table contains counts of each of those different kinds of entries.

Oh, and at the top of the loop

     let entry = journal[i], index = 0;

that's just a declaration of entry and index.

like image 177
Pointy Avatar answered Mar 08 '26 01:03

Pointy


let entry = journal[i], index = 0

is shorthand for

let entry = journal[i];
let index = 0;

it works similarly for var, const and global declarations:

var entry = journal[i], index = 0

would translate to

var entry = journal[i];
var index = 0;
like image 28
Namaskar Avatar answered Mar 08 '26 01:03

Namaskar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!