Check For The Presence of an Element With indexOf

Tell us what’s happening:
First of all, it felt nice to write this up with only the return and using the ternary operator right off and not after refactoring. I’m curios to know though if there is a difference between my solution and:

if (arr.indexOf(elem) < 0) {
    return false;
  } else {
    return true;
  }

other than looking cleaner? Like would it run any faster?

Your code so far


function quickCheck(arr, elem) {
  return (arr.indexOf(elem) < 0) ? false : true;
}

// change code here to test different cases:
console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof

It’ll be using the equivalent of if/else under the hood anyway, and any difference in speed is likely to be by an almost infitesimally small amount.

Note the returning true/false is unecessary, you can just do

return arr.indexOf(elem) !== -1;
// or
return arr.indexOf(elem) > -1;
// or
return arr.indexOf(elem) >= 0;
1 Like

Another one you can use is:

return arr.includes(elem)

This is a relatively new method (ES7), so it’s unlikely to work in IE, but should work in any modern browser.

1 Like

Yep I would always use that, I want sure if using indexOf was part of the challenge though (and come to think of it, the explicit true/false return, I should have checked)

There’s always ~arr.indexOf(elem) if you like bit twiddling as well

1 Like

@DanCouper indexOf() was part of this challenge but still thanks to you and @chuckadams cause all of these are great. I really like refactoring and making the code as short and purdy as I can and it makes me feel like I know something.

1 Like