In this quick tutorial i am going to explain check if an object has a property in javascript. Sometimes in our javascript code we need to check that an object has a property in javascript or not. In this example i will share three ways to check javascript object property. From this lesson you will also learn how to check if an object has a specific property in javascript.
In the first example i will show you hasownproperty with source code:
const language = {
name: 'react'
};
language.hasOwnProperty('name'); // => true
language.hasOwnProperty('framework'); // => false
language.hasOwnProperty('name')
returns true
because the property name
exists in the object language
. Let’s use in
operator to detect the existence of name
and framework
in language object in my second example:
const language = {
name: 'react'
};
'name' in language; // => true
'framework' in language; // => false
Read also: How to Do Object Destructuring in JavaScript
Hope it can help you.
#javascript