Ads by ProfitSence
Close

Checking if an Object has a property JavaScript

Last Updated on Wednesday 5th Oct 2022

in operator

  • Use the in operator to look for a property by name.
			
					const book = {
    name: "One Last Stop",
    author: "Casey McQuiston",
    year: 2021
}

			
	

The Below Code runs because there is in book.name property

			
					if ('name' in book) {
    ....Do Something
}

			
	

The Below code does not run because there is no total in the book.total property

			
					if ('total' in book) {
    ....Do Something
}

			
	
  • If You attempt to get a property that does not exist, you get the undefined value.
  • The in operator searches an object and its prototype chain.

hasOwnProperty() method

  • You Can use the hasOwnProperty() method, which only searches the current object.
			
					const book = {
    name: "The Paper Palace: A Novel",
    author: "Miranda Cowley",
    year: 2021
}

			
	
			
					// console.log(book.hasOwnProperty("name")) // true
// console.log(book.hasOwnProperty("total")) // false