Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Explain the purpose of the ‘in’ operator in JavaScript

  • Last Updated : 09 Nov, 2021

In this article, we will discuss about the in operator available in JavaScript. The in operator is used to check whether the data is within the object or in an array. In an object, the in operator works only on the key or property of the object. If the key or property exists then this operator returns true otherwise false. Similarly for arrays, it will return true if we pass the index of the element not for a particular value.

The below examples will help you understand the uses of the operator.

Example 1: Using the in operator with objects.  Let’s create an object first, to create an object we have to assign key-value pairs.

const object = {
    User: 'Geek',
    Website: 'GeeksforGeeks',
    Language: 'JavaScript'
};

We will check whether the key exists in the object or not by using the in operator.

JavaScript




<script>
    const object = {
        User: 'Geek',
        Website: 'GeeksforGeeks',
        Language: 'JavaScript',
    };
  
    if ('User' in object) {
        document.write("Found");
    }
    else {
        document.write("Not found");
    }
</script>

Output: We have checked if the ‘User’ key is in the object or not, if it is in the object then print Found otherwise Not found.

Found

Example 2: Using the in operator with arrays. Let’s create an array first, to create an array we have to assign values to the array in square brackets.

const array1 = ["Geek", "GeeksforGeeks", "JavaScript"];

We will check whether the index value exists in the array or not,

JavaScript




<script>
    const array1 = ["Geek", "GeeksforGeeks", "JavaScript"];
    if (1 in array1) {
        document.write("Found: ", array1[1]);
    }
    else {
        document.write("Not found");
    }
</script>

Output: We have checked if index 1 is present in the array or not.

Found: GeksforGeeks

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!