Variables combined in one line of indexOf method (Eloquent Javascript)

484 views Asked by At

I felt confused about the following function from Eloquent Javascript

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

What does entry.events.indexOf(event) mean?

3

There are 3 answers

2
Scimonster On BEST ANSWER

entry is an object with an events property (which is probably an array). events has the method indexOf. You then check the index of event in events, and compare against -1.

It's not combing variables, just accessing object properties.

0
Alex McMillan On

event and entry are variables, events is a property of the object referenced by the entry variable.

Arrays and strings in Javascript provide an indexOf method which searches the Array or string referenced for the value and returns its index.

For example:

"one two three".indexOf("two"); // 4

and

[21, 15, 99].indexOf(99); // 2
4
Jack F On

indexOf() is a standard method on arrays. Quoting Mozilla:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

So the hasEvent() function is simply checking if the value of event exists in the entry.events array.

N.B. indexOf() is also a standard method on JavaScript String objects. Again quoting Mozilla:

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex [an optional second parameter]. Returns -1 if the value is not found.

If typeof entry.events === 'string' returns true then the hasEvent() function will check if the value of event exists anywhere in the entry.events string.