Eloquent javascript chapter 4

Hey guys! 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

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;

You can do multiple let assignments in one line, separated by a comma

Personally I consider that bad style, but others think the space saving “benefit” is worth it if declaring a lot of variables

It’s more commonly seen in older js from my experience, where because of the hoisting of var a lot of people choose to declare all variables right at the start of a function

2 Likes

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

is same as:
let entry = journal[i];
let index = 0;

index += 2 ; // is same as index = index + 2; //+= is shortcut for adding value to itself and then assigning new value to itself;

table[index] += 1; does few things
1)get table element at position index;
2)add 1 to that element and assign new value to itself;

1 Like