Bird
0
0

Consider this Angular component snippet:

medium📝 component behavior Q13 of 15
Angular - Lifecycle Hooks
Consider this Angular component snippet:
items = [1, 2, 3];

ngDoCheck() {
  if (this.items.length !== this.oldLength) {
    console.log('Items changed');
    this.oldLength = this.items.length;
  }
}

What will be logged if items.push(4) is called and Angular runs change detection?
AError: oldLength is undefined
BNothing is logged
CItems changed twice
DItems changed
Step-by-Step Solution
Solution:
  1. Step 1: Check initialization of oldLength

    The code uses this.oldLength but it is never initialized, so it's undefined initially.
  2. Step 2: Runtime behavior after items.push(4)

    this.items.length becomes 4, and 4 !== undefined is true, so 'Items changed' is logged. No error occurs.
  3. Final Answer:

    Items changed -> Option D
  4. Quick Check:

    4 !== undefined -> true, logs [OK]
Quick Trick: Always initialize variables used in ngDoCheck before use [OK]
Common Mistakes:
  • Assuming oldLength is automatically defined
  • Expecting ngDoCheck to detect changes without setup
  • Thinking accessing undefined properties causes runtime errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes