JavaScript “in” keyword is used to check if a given property exists in an object. It returns true
if the property exists, and false
if it doesn’t.
property in object
Note: the in
keyword only checks for the existence of a property, not its value. To check for the value of a property, you can use other operators such as ===
or !==
.
JavaScript in keyword example
A simple example code uses the in
keyword to check if the name
property exists in the person
object.
<!DOCTYPE html>
<html>
<body>
<script>
let person = {
name: 'John',
age: 30,
isStudent: false
};
if ('name' in person) {
console.log('Name property exists in object');
} else {
console.log('Name property does not exist in object');
}
</script>
</body>
</html>
Output:
We can also use the in
keyword to check if a property exists in an array. But you have to use the index number of the element you want to check for existence in Array.
let fruits = ['apple', 'banana', 'orange'];
if (1 in fruits) {
console.log('Second element exists in array');
} else {
console.log('Second element does not exist in array');
}
Comment if you have any doubts or suggestions on this Js 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