Mukul Sharma Mukul Sharma - 1 month ago 7
TypeScript Question

array initialization in angular 2, Typescript

when I am initializing array globally (outside the method) its working fine. but when I am initializing the same array inside the method its throwing error unexpected token. you can see into code for location of array. this is array calculateResult[] = [];

Screenshot error

private log: string ='result';
private kw: string = 'kw';
private frame: number = 0;
public finalResult[] = [];

//here this array is working fine
calculateResult[] = [];


//if i initialize this array here, it's throwing error
// calculateResult[] = [];

this.log = '1SE0 070-2NC70' '\n' = '.37' '\n'
this.frame = '71' '\n'

this.calculateResult[0] = this.log;
this.calculateResult[1] =;
this.calculateResult[2] = this.frame;


for(i=0;i < this.finalResult.length;i++){

Answer Source

The first declaration is considered as a class property, so it's correct.

The second one, is incorrect because it is inside the class method and thus should be either declared as

let calculateResult=[];

if you intend to declare a new array of that name,

either addressed as the class property declared above as

this.calculateResult = ...

So keep the first one: calculateResult = [];

If you keep it commented, this.calculateResult[0] will be undefined in the class method, you cannot refer it to.

@Faisal made here a helpful input:

Here are some examples of declaring class and function variables/properties:

Inside Class:

private calculateResult  = []; // correct
public calculateResult  = []; // correct 
calculateResult  = []; // correct
let calculateResult  = []; // wrong
const calculateResult  = []; // wrong

Inside a Function:

private calculateResult  = []; // wrong
calculateResult  = []; // wrong
this.calculateResult = []; // correct, initializes global variable
let calculateResult = []; // correct, initializes local variable