Im using the following javascript. it writes fine until it gets to a result which doesn't have a value. in console log it shows this
Uncaught TypeError: Cannot read property 'text' of null
but my script below doesn't seem to work
var checkCaption = photo.caption.text;
if (checkCaption == null) {
caption = 'meh';
} else {
caption = photo.caption.text;
}
Im using the following javascript. it writes fine until it gets to a result which doesn't have a value. in console log it shows this
Uncaught TypeError: Cannot read property 'text' of null
but my script below doesn't seem to work
var checkCaption = photo.caption.text;
if (checkCaption == null) {
caption = 'meh';
} else {
caption = photo.caption.text;
}
Share
Improve this question
asked Oct 7, 2012 at 16:02
ngplaygroundngplayground
21.6k37 gold badges98 silver badges174 bronze badges
5 Answers
Reset to default 21In your example, photo.caption
is null, so your code breaks on the photo.caption.text
call, before the check is done.
var caption;
if(photo.caption != null) { // Covers 'undefined' as well
caption = photo.caption.text;
} else {
caption = "meh";
}
In my case i use the JSON.stringify to check I have received {} (null) response from the REST server:
if (JSON.stringify(response.data)=='{}') {
//the response is null
}
else {
//the response of JSON is not null
}
It works fine for me to check if the response is null or not.
For me the check of length of the json object resolved the issue -
if Object.keys(jsonobj).length == 0){
// JSON object is null
}
else {
// JSON object has data
}
I know it's pretty late but it might help someone else. you can do this in one line
var checkCaption = photo.caption?.text ?? 'meh';
You can also use
if ("caption" in photo) {
caption = photo.caption?.text
} else {
caption = "meh"
}