Search code examples
javascriptangularconstructorlifecycle

Angular field initialization vs constructor initialization?


Do fields need to be initialized using the constructor for angular components? A lot of angular tutorials do:

counter: number;

constructor() {
    this.counter = 1;
}

Instead of just counter: number = 1.


Solution

  • Both are correct programming wise,

    Initialized within the constructor

    It would be good practice to initialized within the constructor , it's kind of code separation of declaration + initialization .

    That will increase your code readability and you will be sure that all values initialized within the constructor only. and because in the constructor is when the object is created, and it is when the variable should initialized.


    Initialized outside the constructor

    One issue with initialized using the constructor is , more code to write , when you have alot variable to work with , in that case you should use direct counter: number = 1 , In this case you can check declaration + initialization in single line , but in above case you have to go through 2 steps declaration + initialization

    It really matters when you choose initialisation within one of the life cycle hook (E.g. NgOnInit / NgAfterViewInit) vs the constructor. Either it's just a coding style