How to create an array in javascript and get an element by index ?

Active February 14, 2022    /    Viewed 177    /    Comments 0    /    Edit


Examples of how to create an array in javascript and get an element by index:

Create an array in javascript

Examples of how to create arrays in javascript

var data_1 = [1,2,3,4];

var data_2 = [1,['Ben','Tom','Jess'],3,4];

var data_3 = [[1,2],[3,4],[5,6]];

Get array length

To get array's length:

data_1.length;

gives

4

For the second array

data_2.length;

gives

4

and the the third array:

data_2.length;

gives

3

Check if it is an array

Using Array.isArray()

A solution to check if a javascript variable is an array is to use Array.isArray()

var data = [1,2,3,4];

Array.isArray(data);

returns here

true

while

data = 3;

returns

False

Using console.assert()

Another solution to debug a code is to use console.assert()

console.assert( Array.isArray(data), {errorMsg: 'Warning: not an array !'} );

Here it will return nothing since data is an array,

Now if we change data variable to:

data = 'Hello World';

then

console.assert( Array.isArray(data), {errorMsg: 'Warning: not an array !'} );

will returns the folling error message:

Assertion failed: {errorMsg: 'Warning: not an array !'}

Get array element by index

To get array element by index (Note: arrays are 0-based indexing in javascript):

Array 1

data_1[0];
1
data_1[1];
2
data_1[2];
3
data_1[3];
4
data_1[5];
undefined

Array 2

data_2[0];
1
data_2[1];
(3) ['Ben', 'Tom', 'Jess']
data_2[2];
3
data_2[3];
4

Note that:

Array.isArray(data_2[0]);
false

and

Array.isArray(data_2[1]);
true

Array 2

data_2[0];
1
data_2[1];
(3) ['Ben', 'Tom', 'Jess']
data_2[2];
3
data_2[3];
4

Note that:

Array.isArray(data_2[0]);
false

and

Array.isArray(data_2[1]);
true

Array 3

data_3[0];
(2) [1, 2]
data_3[0][0];
1
data_3[0][1];
2
data_3[1];
(2) [3, 4]
data_3[1][0];
3
data_3[1][1];
4

Using a for loop

An example using a for loop to iterate over array elements:

for (let i = 0; i < data_1.length; i++) {
    console.log(data_1[i]);
};
1
2
3
4

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount