Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 705
Red Cricket Avatar asked Oct 26 '25 18:10

Red Cricket


1 Answers

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');
like image 97
CertainPerformance Avatar answered Oct 29 '25 09:10

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!