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
}
}
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.
Yes, you can also initialize these values using the 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.
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.
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/
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With