Red Cricket
Red Cricket

Reputation: 10470

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

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?

Upvotes: 4

Views: 9633

Answers (4)

Evan Darwin
Evan Darwin

Reputation: 860

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
}

Upvotes: 3

Zaphiel
Zaphiel

Reputation: 293

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.

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 371098

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');

Upvotes: 11

aceraven777
aceraven777

Reputation: 4556

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.

Upvotes: 2

Related Questions