JavaScript中用if(variable)检测undefined失效触发TypeError问题咨询
Hey there, let's figure out why you're hitting that TypeError and how to fix it properly.
First off, the root cause of your TypeError is that the logical OR (||) only short-circuits when the left side evaluates to true. But if body is a truthy value that doesn't support index access (like a number 123, boolean true, or plain object {}), !body will return false, so the code tries to run body[0]—and those types can't be accessed with numeric indexes, hence the error.
For example:
const body = 123; !body || body[0] === '<'; // !123 is false, so we try body[0] and get a TypeError
Your original logic was meant to check if body is null/undefined, or doesn't match your expected value—but the gap is that you didn't account for truthy values that aren't strings/arrays (the only types where [0] makes sense).
Fixes to Avoid the TypeError
1. Validate the type before accessing the index
First check if body is a string (since it looks like you're expecting HTML-like content) before trying to access its first character:
// Checks if body is null/undefined, OR it's a string starting with '<' const isValid = (body == null) || (typeof body === 'string' && body[0] === '<');
Note that body == null is the standard, concise way to check for both null and undefined—it's more precise than !body because it won't treat 0, empty strings, or false as "missing" values.
2. Use the Optional Chaining Operator (ES2020+)
If you're working in an environment that supports modern JS, the optional chain (?.) is perfect here. It safely accesses the index: if body is null/undefined, it returns undefined instead of throwing an error. Even if body is a non-indexable truthy value, it'll just return undefined without crashing:
const isValid = !body || (body?.[0] === '<');
3. Standard Utility Functions (if you prefer)
If you don't want to write custom checks, libraries like Lodash have built-in functions for safe property access. For example, _.get:
// After installing Lodash const isValid = !body || (_.get(body, '[0]') === '<');
That said, optional chaining is a native ES standard now, so it's usually the simplest choice without adding dependencies.
Quick Recap of Why Your Original Code Failed
!body returns true for null, undefined, NaN, empty strings, 0, and false—in those cases, the right side never runs. But when body is a truthy value that can't be indexed (like an object or number), !body is false, so the code tries body[0] and throws the TypeError.
内容的提问来源于stack exchange,提问作者oystersauce

