Using '!== undefined' and '> -1' difference

I’ve always used ‘!== undefined’ to express if something exists, however in this exercise it uses ‘> -1’. Is my way ok? When is it ok to use either or? Is my reasoning of the code (in the comments) valid?

function findAgent(agentList, agentToSearchFor) {
  if(agentList[agentToSearchFor] !== undefined) // if agentToSearchFor inside agentList exists
 return agentToSearchFor + ' is present within Agent list' // return agentToSearchFor + ' is present within Agent list'
} // my code



function findAgent(agentList, agentToSearchFor) {
  if(agentList.indexOf(agentToSearchFor) > -1) //if agentToSearchFor's index (in agentList) exists
 return agentToSearchFor + ' is present within Agent list' // return agentToSearchFor + ' is present within Agent list'
} // their code

It depends on whether agentList is an array or an object. If it is an object, you can use

if(agentList[agentToSearchFor] !== undefined)

but you typically would use hasOwnProperty() instead (because it’s possible for the key to exist but not contain a value).

If agentList is an array, then you would check whether something is in that array with indexOf(), which returns a number. If an item is not in the array, then indexOf() will return -1.

2 Likes