Close
Close full mode
logoWebDevAssist

How to create an empty array in TypeScript

How to create an empty array in TypeScript:

We can create an empty array, or we can create one array with predefined size with empty values. In this post, we will learn how to create an empty array in TypeScript.

Create an empty array:

We can initialize an array as empty as like below:

let arr : string[] = []
console.log('Given array: ',arr);

It will print:

Given array: []

The size of the array is 0. If you run the below program:

let g : string[] = []
console.log('Given array: ',g.length);

It will print 0.

We can keep pushing other values to the array:

let g : string[] = []
g.push('a')
g.push('b')
console.log('Given array: ',g.length);

It will keep increasing the array size. The above program will print 2.

And, if we add any item using an index, it will update the size. For example:

let g : string[] = []
g[20] = 'hello'
console.log('Given array: ',g.length);

It is inserting the element at index 20 of this empty array. It will update the length to 21 and the console.log statement will print 21.

Empty array of specific size:

We can also create an empty array of specific size:

let g : string[] = new Array(4);
console.log('Given array: ',g.length);

It will create one empty array of size 4. All values in this array are empty.

Specific size empty array filled with values:

If you want to have an empty array, but want to fill each value with something different, e.g. with empty strings, you can do that as like below:

let g : string[] = new Array(4).fill('');
console.log('Given array: ',g);

It will fill the array with empty strings.

Given array: ["", "", "", ""]

Subscribe to our Newsletter

Previous
How to remove the last element from an array in TypeScript
Next
How to remove the first element from an array in TypeScript