如何安全简洁地输出可能未定义的root对象的uri属性?
root.uri Great question! Dealing with optional properties or potentially undefined values is a super common scenario in JavaScript, and there are a couple of clean, safe approaches to solve this based on your environment.
1. Use Optional Chaining (ES2020+)
This is the most concise and modern solution, widely supported in modern browsers and Node.js (v14+). The optional chain operator (?.) safely accesses the uri property only if root exists (is not undefined or null). If not, it returns undefined instead of throwing an error:
console.log('root.uri = ' + root?.uri);
If you want a friendly fallback instead of undefined when uri is missing, pair it with the nullish coalescing operator (??):
console.log('root.uri = ' + (root?.uri ?? 'URI not available'));
Unlike ||, ?? only falls back if the left-hand side is undefined or null—it won't trigger for valid falsy values like 0 or empty strings.
2. Compatibility-Friendly Short-Circuit Check
If you need to support older environments without ES2020 features, use a logical short-circuit to verify root exists before accessing uri:
console.log('root.uri = ' + (root && root.uri || 'URI not available'));
This works because && stops evaluating if root is falsy (like undefined), avoiding the "Cannot read property 'uri' of undefined" error. The || then provides a fallback if either root or root.uri is falsy.
Quick Context Fit
Since root is assigned either resolvedRoot or the result of an await call, the optional chain approach is perfect here—it handles both cases where resolvedRoot might be undefined, or the resolved value from getCurrentUserHome() lacks an uri property.
内容的提问来源于stack exchange,提问作者Socrates

