July 4, 2020
How to Check if Key is Present in Object Javascript
- We have selected two elements
button
andh1
using thedocument.querySelector()
method and stored them inbtnCheck
andresult
variables respectively. - We have a global variable
obj
and it holds an object as its value. - We have attached the
click
event listener to thebutton
element. - In the
click
event handler function, we are using thehasOwnProperty()
method to check if there is a property with a keyname
. - We are setting the inner text of the
h1
element to the Boolean value returned by thehasOwnProperty()
method.
let btnCheck = document.querySelector('button'); let result = document.querySelector('h1'); let obj = {name:'Marks', age: 27}; btnCheck.addEventListener('click', () => { result.innerText = obj.hasOwnProperty('name') ? 'True' : 'False'; });