2

Is there a Javascript equivalent to Python's in conditional operator?

good = ['beer', 'pizza', 'sushi']
thing = 'pizza'
if thing in good:
    print 'hurray'

What would be a good way to write the above Python code in Javascript?

Red Cricket
  • 9,762
  • 21
  • 81
  • 166
  • Possible duplicate of [Determine whether an array contains a value](https://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value) – faintsignal Jun 01 '18 at 03:34

4 Answers4

7

You can use .includes:

const good = ['beer', 'pizza', 'sushi']
const thing = 'pizza';
if (good.includes(thing)) console.log('hurray');

Note that this is entirely separate from Javascript's in operator, which checks for if something is a property of an object:

const obj = { foo: 'bar'}
const thing = 'foo';
if (thing in obj) console.log('yup');

Note that includes is from ES6 - make sure to include a polyfill. If you can't do that, you can use the old, less semantic indexOf:

const good = ['beer', 'pizza', 'sushi']
const thing = 'pizza';
if (good.indexOf(thing) !== -1) console.log('hurray');
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
3

If you're using JavaScript ES6, I believe that Array.includes is what you're looking for. If you need support for older versions of JS, then you can use Array.indexOf (or use a polyfill for Array.contains).

// Array.includes()
if (yourArray.includes("some value")) {
    // Do stuff
}

// Array.indexOf()
if (yourArray.indexOf("some value") > -1) {
    // Do stuff
}
faintsignal
  • 1,828
  • 3
  • 22
  • 30
Evan Darwin
  • 850
  • 1
  • 8
  • 29
2

A simple google search will answer your question. Found this in google #1 search https://www.w3schools.com/jsref/jsref_indexof_array.asp.

You can use indexOf method in javascript to find elements in your array.

aceraven777
  • 4,358
  • 3
  • 31
  • 55
  • 1
    This is a comment and/or a close vote or down vote, not an answer. –  Jun 01 '18 at 03:52
2

You can check using indexOf() method.
Example:

const good = ['beer', 'pizza', 'sushi']
const thing = 'pizza';

if(good.indexOf(thing) !== -1)
//do something

if it's matches, will return the very first index. If not, will return -1.

Quick note:
indexOf() method comes with ECMAScript 1 so it will be compatible with all browsers. But includes() method comes witch ECMAScript 6 and maybe cannot be compatible on some platforms/older browser versions.

Zaphiel
  • 294
  • 3
  • 11