Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptExplain the purpose of the ‘in’ operator in JavaScript

Explain the purpose of the ‘in’ operator in JavaScript

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: 'neveropen',
    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: 'neveropen',
        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", "neveropen", "JavaScript"];

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

JavaScript




<script>
    const array1 = ["Geek", "neveropen", "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: neveropen

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments