Languages
[Edit]
EN

JavaScript - create array

3 points
Created by:
lena
714

This article will show you how to create an array in JavaScript.

Quick solution:

const arrayName = [element1, element2, element3, elementN];

 

Practical examples

// ONLINE-RUNNER:browser;

const myArray = ['Tom', 'Kate', 'Mary'];

console.log(myArray);  // Tom,Kate,Mary

 The above creation of an array can also be written as follows:

// ONLINE-RUNNER:browser;

const myArray = [
    'Tom', 
    'Kate', 
    'Mary'
];

console.log(myArray);  // Tom,Kate,Mary

 or:

// ONLINE-RUNNER:browser;

const myArray = [];

myArray[0] = 'Tom';
myArray[1] = 'Kate';
myArray[2] = 'Mary';
// null on 3rd and 4th positions
myArray[5] = 'John';

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:

// ONLINE-RUNNER:browser;

const myArray = Array(3);

myArray[0] = 'Tom';
myArray[1] = 'Kate';
myArray[2] = 'Mary';

console.log(myArray);  // Tom,Kate,Mary

Note: this approach allocates necessary array space during array creation - not necessary resize in memory later.

or:

// ONLINE-RUNNER:browser;

const myArray = new Array('Tom', 'Kate', 'Mary');

console.log(myArray);  // Tom,Kate,Mary

Note: the constructor-based approach used a much less frequent approach.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Arrays (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join