Do JavaScript arrays have an equivalent of Python’s \"if a in list\"?

JavaScript provides the includes() method as the direct equivalent of Python's if item in list syntax. This method returns true if the element exists in the array, otherwise false.

In Python, you check membership using:

# Python syntax
if "apple" in fruits:
    print("Found!")

JavaScript achieves the same result with the includes() method, which is supported in all modern browsers and provides a clean, readable solution.

Syntax

array.includes(searchElement, fromIndex)

Parameters

  • searchElement ? The element to search for in the array
  • fromIndex (optional) ? The position to start searching from. Defaults to 0

Return Value

Returns true if the element is found, false otherwise.

Basic Example

<!DOCTYPE html>
<html>
<body>
   <p id="result1"></p>
   <p id="result2"></p>
   <script>
      let fruits = ['apple', 'banana', 'orange'];
      
      // Check if 'banana' exists
      document.getElementById("result1").innerHTML = "Contains 'banana': " + fruits.includes('banana');
      
      // Check if 'grape' exists  
      document.getElementById("result2").innerHTML = "Contains 'grape': " + fruits.includes('grape');
   </script>
</body>
</html>
Contains 'banana': true
Contains 'grape': false

Using Starting Index

<!DOCTYPE html>
<html>
<body>
   <p id="demo"></p>
   <script>
      let numbers = [1, 2, 3, 4, 5, 2];
      
      // Search from beginning
      let found1 = numbers.includes(2);
      
      // Search from index 2 onwards
      let found2 = numbers.includes(2, 2);
      
      document.getElementById("demo").innerHTML = 
         "Found from start: " + found1 + "<br>" +
         "Found from index 2: " + found2;
   </script>
</body>
</html>
Found from start: true
Found from index 2: true

Alternative Methods

Method Returns Use Case
includes() Boolean (true/false) Check existence only
indexOf() Index number or -1 Find position of element
find() Element or undefined Complex conditions with callback

indexOf() Alternative

let colors = ['red', 'green', 'blue'];

console.log(colors.indexOf('green') !== -1);  // true
console.log(colors.indexOf('yellow') !== -1); // false

// More readable with includes()
console.log(colors.includes('green'));   // true
console.log(colors.includes('yellow'));  // false
true
false
true
false

Conclusion

The includes() method is JavaScript's direct equivalent to Python's in operator for arrays. It provides clean, readable code and better performance than indexOf() for simple existence checks.

Updated on: 2026-03-15T23:19:00+05:30

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements