Manu Chadha
Manu Chadha

Reputation: 16755

Is there a difference if a variable is initialized at the point of declaration or in the constructor

If I have a variable isEditing, I can initialize it either at point of declaration

isEditing:boolean = false;

or inside a constructor

constructor(){
this.isEditing= false
}

Is there a difference between the the approaches?

Upvotes: 1

Views: 34

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075925

There's no runtime difference, no. Property initializers are relocated to the beginning of the constructor, in source-code order, just after any call to super if required. (JavaScript's own property declarations will work effectively the same way.)

Both this TypeScript:

class Example {
    public answer: number = 42;
}

and this TypeScript:

class Example {
    public answer: number;
    constructor() {
        this.answer = 42;
    }
}

compile to this JavaScript (when targeting ES2015+):

class Example {
    constructor() {
        this.answer = 42;
    }
}

Upvotes: 3

Related Questions