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?
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?
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
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.
entryis an object with aneventsproperty (which is probably an array).eventshas the methodindexOf. You then check the index ofeventinevents, and compare against -1.It's not combing variables, just accessing object properties.