Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing variables inline during declaration vs in the constructor in Angular with TS

I have been working for a while with Angular but can't find a definitive recommendation on :

Initializing member variables inline vs in the constructor

I had a couple of times my code reviewed to move initialization of simple types (boolean, number, etc.) in the constructor, but still wonder whether this is the better practice or a matter of taste? For me inline initialization results in more localized and concise code, that's why I prefer it, but am I right or not ?

Example:

@Component({
  selector: 'app-elem',
  templateUrl: './app-elem.component.html',
  styleUrls: ['./app-elem.component.scss'],
})
export class AppElemComponent {

  public isHidden = true;    // <-- initialization inline
  public isVisible: boolean;

  constructor() {
    this.isVisible = true;  // <-- vs initialization in the constructor
  }
}
like image 828
zaggi Avatar asked Jul 24 '18 08:07

zaggi


People also ask

What is the difference between declaring and initialising a variable?

Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable.

Can we initialize variable in constructor?

Yes, you can also initialize these values using the constructor.

Why do we initialize variable in constructor?

It makes sense to initialize the variable at declaration to avoid redundancy. It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors.

Which variables are initialized inside a method block or constructor?

Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.


Video Answer


2 Answers

It's a personal style preference.

Initializing a property in the constructor allows you to leverage constructor parameters when you're initializing the property.

Initializing a property inline is more concise, and keeps the default value of the property more in context with its declaration.

TypeScript compiler just brings values initialized inline inside the constructor https://www.typescriptlang.org/play/

like image 99
Roy G Avatar answered Sep 29 '22 20:09

Roy G


There is no difference basically, its just the convenience. Only difference for using constructor initialization is you can pass the value dynamically and then assign to it.

constructor(visible) {
    this.isVisible = visible;  // <-- vs initialization in the constructor
}
like image 27
Amit Chigadani Avatar answered Sep 29 '22 20:09

Amit Chigadani