Bird
0
0

How can you write a template expression that safely displays the length of an array items which might be null or undefined?

hard📝 component behavior Q8 of 15
Angular - Templates and Data Binding
How can you write a template expression that safely displays the length of an array items which might be null or undefined?
A{{ items?.length ?? 0 }}
B{{ items.length }}
C{{ items?.length || 'empty' }}
D{{ items.length ?? 0 }}
Step-by-Step Solution
Solution:
  1. Step 1: Handle possible null or undefined array

    Use safe navigation operator (?.) to avoid errors if items is null or undefined.
  2. Step 2: Provide default value if length is undefined

    The nullish coalescing operator (??) returns 0 if items?.length is null or undefined.
  3. Final Answer:

    {{ items?.length ?? 0 }} -> Option A
  4. Quick Check:

    Use ?. and ?? to safely access and default values [OK]
Quick Trick: Combine ?. and ?? to safely access and default values [OK]
Common Mistakes:
  • Not using safe navigation causing runtime errors
  • Using || which treats falsy values incorrectly
  • Accessing length without null checks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes