Skip to content
Related Articles
Open in App
Not now

Related Articles

Explain the purpose of the ‘in’ operator in JavaScript

Improve Article
Save Article
  • Last Updated : 09 Jan, 2023
Improve Article
Save Article

JavaScript 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) {
        console.log("Found");
    }
    else {
        console.log("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) {
        console.log("Found: ", array1[1]);
    }
    else {
        console.log("Not found");
    }
</script>


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

Found: GeeksforGeeks

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!