EN
JavaScript - create array
3 points
This article will show you how to create an array in JavaScript.
Quick solution:
xxxxxxxxxx
1
const arrayName = [element1, element2, element3, elementN];
xxxxxxxxxx
1
const myArray = ['Tom', 'Kate', 'Mary'];
2
3
console.log(myArray); // Tom,Kate,Mary
The above creation of an array can also be written as follows:
xxxxxxxxxx
1
const myArray = [
2
'Tom',
3
'Kate',
4
'Mary'
5
];
6
7
console.log(myArray); // Tom,Kate,Mary
or:
xxxxxxxxxx
1
const myArray = [];
2
3
myArray[0] = 'Tom';
4
myArray[1] = 'Kate';
5
myArray[2] = 'Mary';
6
// null on 3rd and 4th positions
7
myArray[5] = 'John';
8
9
console.log(myArray); // Tom,Kate,,,Mary // use JSON.stringify(myArray) to see null values
Note: this approach will cause automatic array resizing on assigning new indexes - by assigning non consecutive indexes, the array will be filled in unused areas with
null
values.
or:
xxxxxxxxxx
1
const myArray = Array(3);
2
3
myArray[0] = 'Tom';
4
myArray[1] = 'Kate';
5
myArray[2] = 'Mary';
6
7
console.log(myArray); // Tom,Kate,Mary
Note: this approach allocates necessary array space during array creation - not necessary resize in memory later.
or:
xxxxxxxxxx
1
const myArray = new Array('Tom', 'Kate', 'Mary');
2
3
console.log(myArray); // Tom,Kate,Mary
Note: the constructor-based approach used a much less frequent approach.