Skip to content

JavaScript in operator array | Example code

  • by

JavaScript in operator used in an array to check specified index or its prototype chain. The in operator will return false for empty array slots. Even if accessing it directly returns undefined.

For example, you can use the in operator to check if a property exists in an object:

const person = {
  name: 'John',
  age: 30,
};

console.log('name' in person); // true
console.log('address' in person); // false

However, if you want to check if an element exists in an array, you can use the Array.prototype.includes() method introduced in ECMAScript 2016 (ES7) or the Array.prototype.indexOf() method.

Here’s an example using the includes() method:

const fruits = ['apple', 'banana', 'orange'];

console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape')); // false

And here’s an example using the indexOf() method:

const fruits = ['apple', 'banana', 'orange'];

console.log(fruits.indexOf('banana') !== -1); // true
console.log(fruits.indexOf('grape') !== -1); // false

These methods return a boolean value indicating whether the element is found in the array or not.

JavaScript in operator array

A simple example code shows some uses of the in operator.

<!DOCTYPE html>
<html>
<body>

  <script>
   let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']
   
   console.log(0 in trees)        
   console.log(3 in trees)       
   console.log(6 in trees)     
   console.log('bay' in trees) //returns false (you must specify the index number, not the value at that index)

 </script>

</body>
</html> 

Output:

JavaScript in operator array

Why does javascript’s “in” operator return true when testing if 0 exists in an array that doesn’t contain 0?

Answer: Javascript’s in operator does not check if a value is contained in an array.

The in operator doesn’t do what you think it does. The in operator returns true if the specified operand is a property of the object. For arrays, it returns true if the operand is a valid index (which makes sense if think of arrays as a special-case object where the properties are simply named 0, 1, 2, …)

For example, try this:

var x=[1,4,6];
alert(2 in x);

It’ll also return true, because “2” is a valid index in the array. In the same way, “0” is an index in the array, so also returns true.

Do comment if you have any doubts or suggestions on this JS “in” operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *