-4

I understand practically all of this code except the lines noted below

function hasEvent(event, entry) {
  return entry.events.indexOf(event) != -1; /*?????????*/
}

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

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

JOURNAL is an array. This function loops through it to find if any of the entries hold the value of pizza, and what the value of the property of squirrel is. Based on the results of those two checks, 1 is added to one of the 4 index in table. I guess I'm not understanding what the hasEvent function does, and how it interacts with the first if statement.

For more details, code can be found about halfway through this page

http://eloquentjavascript.net/04_data.html

Mark Romano
  • 701
  • 3
  • 12
  • 25

1 Answers1

5

In JS, an array function indexOf returns -1 if the element you are searching the index of does not exists. It will not return 0 because 0 is a valid index.

Ron Dadon
  • 2,666
  • 1
  • 13
  • 27
  • So what does the != do at the end of the first function? Is it saying, if the index of the event isn't found, return -1? If so, why isn't it prepended with an `if` statement? Also - what causes the first `if` statement in the `tableFor` function to become true or false? – Mark Romano Dec 18 '16 at 08:58
  • I believe you are missing some very basic programming skills, regardless of JS. `!=` is `not equal`, and returning `entry.events.indexOf(event) != -1` mean return `true` if the index of event is not equal to -1, meaning event exists. – Ron Dadon Dec 18 '16 at 09:27
  • Ok I understand now. – Mark Romano Dec 18 '16 at 17:36