Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

2. Working with Objects and Properties > Checking If an Object Contains a Given...

Checking If an Object Contains a Given Property Using the in Operator

The in operator is used to verify (true or false) if an object contains a given property. Below, we are checking to see if foo is a property in myObject.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var myObject = {foo: 'value'};
console.log('foo' in myObject); // logs true

</script></body></html>

You should be aware that the in operator not only checks for properties contained in the object referenced, but also for any properties that object inherits via the prototype chain. Thus, the same property lookup rules apply and the property, if not in the current object, will be searched for on the prototype chain.

This means that myObject in the above code actually contains a toString property method via the prototype chain (Object.prototype.toString), even if we did not specify one (e.g., myObject.toString = 'foo').


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint