4

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?

1

5 Answers 5

11

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

Sign up to request clarification or add additional context in comments.

3 Comments

Never knew there was an "includes" method! I usually use indexOf
But indexOf is not entirely equivalent to contains.
The JS includes syntax is not quite as nice as Python IMO.
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
}

Comments

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.

1 Comment

This is a comment and/or a close vote or down vote, not an answer.
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.

Comments

0

Python's in operator not only works with lists, but also with (other) iterables/iterators, and dicts specifically (which are also iterable). If you need that flexibility then use the iterator helper some:

const contains = (haystack, needle) => {
    try {
        return Iterator.from(haystack).some(item => item === needle);
    } catch {
        return Object.keys(haystack).includes(needle);
    }
}

// Different types of inputs:
const plain = { "a": 1, "b": 2, "c": 3 };
const arr = Object.keys(plain);
const str = arr.join("");
const set = new Set(arr);
function* getGenerator() { yield* arr; }
const getIterator = (it=arr.values()) => ({ next: () => it.next() });
const iterable = ({ [Symbol.iterator]: getIterator });

// Run the contains function on those:
console.log("array", contains(arr, "b"), contains(arr, "d"));
console.log("string", contains(str, "b"), contains(str, "d"));
console.log("set", contains(set, "b"), contains(set, "d"));
console.log("plain object", contains(plain, "b"), contains(plain, "d"));
console.log("iterator", contains(getIterator(), "b"), contains(getIterator(), "d"));
console.log("iterable", contains(iterable, "b"), contains(iterable, "d"));
console.log("generator", contains(getGenerator(), "b"), contains(getGenerator(), "d"));

As in JS the (default) Map iterator yields key/value pairs, you'll need to explicitly pass mymap.keys() as argument to contains (and not just mymap) for it to work as the other cases above.

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.