JavaScript中数组变量后、.length前的问号作用解析——关于!isLoading && !QRCodes?.length代码的疑问
?. Operator in !QRCodes?.length Hey there! Let's break down exactly what that ?. is doing in your code, and why it's not redundant even when QRCodes doesn't exist.
First, let's recall what the optional chaining operator (?.) does: it lets you safely access nested properties or methods of an object (or array, in this case) without throwing an error if the parent value is null or undefined.
Let's compare two scenarios side by side:
- Without
?.: IfQRCodesisnullorundefined, trying to accessQRCodes.lengthwill immediately throw aTypeError(something like "Cannot read properties of undefined (reading 'length')"). Your code would crash right here, and the!check never even gets to run. It doesn't returnfalse—it breaks everything entirely. - With
?.: WhenQRCodesisnullorundefined,QRCodes?.lengthreturnsundefinedinstead of throwing an error. Then,!undefinedevaluates totrue(sinceundefinedis a falsy value, negating it gives a true result).
Why does this matter in your specific code?
Your line !isLoading && !QRCodes?.length is checking two conditions together:
- The loading state is finished (
!isLoadingis true) - Either
QRCodesdoesn't exist or it exists but has a length of 0 (since!QRCodes?.lengthis true in both cases)
Without the ?., if QRCodes is null/undefined, the code would crash before it can even verify if loading is complete. The optional chain ensures the check stays safe and your code keeps running as intended.
So to wrap it up: the ?. isn't about altering the boolean result when QRCodes doesn't exist—it's about preventing a runtime error that would halt your code entirely.
内容的提问来源于stack exchange,提问作者Zin Yosrim

