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?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With