The For in array is used to check if a specified property or key exists in an object or an array in JavaScript. When used with an array, the in
operator checks whether a specified index exists in the array. If the index exists, the operator returns true
, otherwise, it returns false
.
index in array
Here, index
is the index number that you want to check for existence in the array
.
Note: that the in
operator does not check whether a specific value exists in the array, but rather whether an element exists at the specified index
For in array JavaScript example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
const myArray = [1, 2, 3];
console.log(0 in myArray);
console.log(3 in myArray);
</script>
</body>
</html>
Output:
Using for...in
for array, iteration is generally considered a bad idea in JavaScript because it can have unintended consequences and cause unexpected behavior.
- It includes non-numeric properties: The
for...in
loop iterates over all enumerable properties of an object, including non-numeric properties such as methods and prototype properties. This means that if you have added custom properties to the array object or its prototype, they will also be included in the iteration. - It iterates over the prototype chain: If you’ve modified the
Array.prototype
object,for...in
will include those properties in the iteration, which can cause unexpected behavior. It’s generally not a good practice to modify built-in object prototypes, and usingfor...in
for array iteration can expose issues that arise from doing so. - It’s slower than other methods:
for...in
loops are slower than other array iteration methods such asfor
loops,Array.prototype.forEach()
, andArray.prototype.map()
. This is becausefor...in
has to check each property in the object, including non-numeric properties.
To avoid these issues, it’s recommended to use other iteration methods that are designed explicitly for arrays, such as for
loops, Array.prototype.forEach()
, Array.prototype.map()
, and Array.prototype.filter()
. These methods are faster and do not include non-numeric properties in the iteration.
Comment if you have doubts or suggestions on this Js “in” keyword topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version