Open In App

Javascript – Catching error if json key does not exist

Last Updated : 11 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss the error handling when a key is not present inside the javascript object.

A JSON is a string format that encloses a javascript object in double-quotes. 

Example:

'{"site": "gfg"}'

A JSON object literal is the javascript object present inside the JSON String. 

Example:

{"site": "gfg"}

The key/value pairs are present inside the JSON Object literal, which is the format to represent javascript objects. In the above example, the key is “site” and the value for this key is “gfg”.

Now, to go back to the problem statement, we have to find if a given key exists inside a javascript object, and give a suitable response corresponding to this condition. Let’s discuss 2 different methods to approach the solution to this problem:

Approach 1: Using the `hasOwnProperty` method:

This method gives a Boolean response; it returns true if the javascript object has its own property* which is passed in its argument, or else it returns false.  

Note: Here, the own property means the property which is defined during the object definition, i.e. defined on the object itself, as opposed to properties inherited from the prototype object.

Example: 

Javascript




let obj = {'key': 'value'}
  
if (obj.hasOwnProperty('key')) {
    console.log(true)
} else {
    console.log(false)
}


Output:

true

Now, this method only works when the obj is not null or undefined. When the obj is null or undefined, we can manipulate the above code to work like this:

Javascript




let obj;
  
if (obj && obj.hasOwnProperty('key')) {
    console.log(true)
} else {
    console.log(false)
}


Output:

false

Here, the && is a Logical AND operator in javascript, which does not allow the javascript interpreter to move forward when it encounters a falsy condition.

Approach 2: Using the `in` property in javascript:

The `in` operator gives a Boolean response, returning true if the specified property is present either directly in the object itself, or in the prototype chain of the object, and otherwise returns false.

Example:

Javascript




let obj = {'key': 'value'}
  
if ('key' in obj) {
    console.log(true)
} else {
    console.log(false)
}


Output:

true

This method also only works when the obj is not null or undefined. For it to work in all cases, manipulate the code in a similar fashion.

Javascript




let obj;
  
if (obj && 'key' in obj) {
    console.log(true)
} else {
    console.log(false)
}


Output: 

false


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads