Bird
0
0

Find the bug in this Angular component: ```typescript export class DemoComponent implements OnInit { ngOnInit() { this.loadData(); } loadData() { console.log(this.data.length); } data: string[]; } ```

medium📝 Debug Q7 of 15
Angular - Lifecycle Hooks
Find the bug in this Angular component: ```typescript export class DemoComponent implements OnInit { ngOnInit() { this.loadData(); } loadData() { console.log(this.data.length); } data: string[]; } ```
Adata should be initialized as an empty array
BngOnInit should not call other methods
Cdata is undefined when loadData runs, causing an error
DConsole.log syntax is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Analyze property initialization

    data is declared but not initialized, so it is undefined by default.
  2. Step 2: Check method call in ngOnInit

    loadData tries to access data.length, but data is undefined, causing a runtime error.
  3. Final Answer:

    data is undefined when loadData runs, causing an error -> Option C
  4. Quick Check:

    Initialize properties before use to avoid errors [OK]
Quick Trick: Initialize arrays before accessing length [OK]
Common Mistakes:
  • Assuming declared properties are auto-initialized
  • Ignoring runtime errors from undefined values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes