if( !body || body[0] === '<') {...}
I am using the above statement to check if a variable body
is undefined
or null or anything but the value that is expected, but I keep getting a TypeError:
TypeError: Cannot read property '0' of undefined
How can this be? According to the very popular answer on checking for undefined the first part !body
of the above statement should return true
if body is anything from null, undefined, NaN, "", 0, or false - and therefore not evaluate the right-hand side of the OR condition: body[0] === '<'
when that is the case.
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
What else could I check for to make sure that body[0]
is only called when body
is not undefined? I also already tried if(typeof body === 'undefined' || body[0] === '<')
with the same described behaviour. Any thoughts on this will be highly appreciated. Thanks you.
(Just for further information: body
is the response of an REST-API request, if everything goes smooth it returns a string that can be parsed into a JSON-object. However, in some cases an entire HTML-file (containing error information) is returned hence I'm checking for '<' at the beginning of the response. Sometimes the variable seems to be 'undefined' which throws the error when checking body[0]
.)