Horje
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: '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



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to find min/max values without Math functions in JavaScript ? How to find min/max values without Math functions in JavaScript ?
How to implement inheritance in ES6 ? How to implement inheritance in ES6 ?
What is Strict Mode and how to enable it in JavaScript ? What is Strict Mode and how to enable it in JavaScript ?
How to use template string literal in ECMAScript 6 ? How to use template string literal in ECMAScript 6 ?
Next.js Pages Next.js Pages

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10