23

If I have a list in Python, I can check whether a given value is in it using the in operator:

>>> my_list = ['a', 'b', 'c']

>>> 'a' in my_list
True

>>> 'd' in my_list
False

If I have an array in JavaScript, e.g.

var my_array = ['a', 'b', 'c'];

Can I check whether a value is in it in a similar way to Python’s in operator, or do I need to loop through the array?

5
  • In other words, I’m asking this question, but for JavaScript instead of Ruby. Commented Sep 16, 2011 at 9:45
  • 2
    possible duplicate: stackoverflow.com/questions/237104/… Commented Sep 16, 2011 at 9:48
  • @6502: ah, that’s the stuff. Write that up into an answer and the points are yours. Commented Sep 16, 2011 at 9:48
  • Check this qeustion. Commented Sep 16, 2011 at 9:49
  • @mouad: great spot — I’m actually using underscore.js, which the top answer to that question mentions, so I might use their function for this. Commented Sep 16, 2011 at 9:49

4 Answers 4

31

Since ES7, it is recommended to use includes() instead of the clunky indexOf().

var my_array = ['a', 'b', 'c'];

my_array.includes('a');  // true

my_array.includes('dd'); // false
Sign up to request clarification or add additional context in comments.

Comments

15
var my_array = ['a', 'b', 'c'];
alert(my_array.indexOf('b'));
alert(my_array.indexOf('dd'));

if element not found, you will receive -1

3 Comments

In modern browser, yes, but older internet explorers does not support it. Here is a question about it (and the workaround): stackoverflow.com/questions/2790001/…
what if searched item exists more than one in an array ?
@Ciastopiekarz indexOf returns the first occurrence: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
3
var IN = function(ls, val){
    return ls.indexOf(val) != -1;
}

var my_array = ['a', 'b', 'c'];
IN(my_array, 'a');

Comments

1

The most current way with ES7 would be the following:

let myArray = ['a', 'b', 'c'];

console.log(myArray.includes('a'))

This will return true or false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.