Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JavaScript 005 – One Dimensional Array

1. Declare One Dimensional Array and Assign Values

An Array in JavaScript can store multiple values. One can declare an One Dimensional Array as follows:

Here, TheNumbers is the variable name of the array. On the right side of the =, the new keyword is used to create the Array. Now-a-days, JavaScript supports a short-hand syntax to create the array:

In the below code, we created the array and initialized it with values. Here. the array contains 4 cells, and in each cell, we have a number. The index operator [] can read a value from the array cell. To read the first element in the below example, we should use it as theNumbers[0].

2. JavaScript One Dimensional Array Example

Now look at the example below:

JavaScript One Dimensional Array Example
JavaScript One Dimensional Array Example

1) Here, we created a JavaScript One Dimensional Array and named it as Persons. Initially, we have three elements in the array, and this is shown in the below picture:

JavaScript Array and Index
JavaScript Array and Index

You can notice that each cell is indexed, and the index start from zero. To access, 2nd person in the Array, we will use the index operator with the array name. For example, Persons[1] refers to the second element in the array called Persons. In the above code, we added person 4 to the array using the statement Persons[3] = “Person 4”. That statement will create a new cell at index location 3 and stores the new person’s name.

2) In the html document, we print person at location 1 and location 4. Since the index starts from zero, we fetched the first person as Persons[0]. The same way we fetch the 4th person from the One Dimensional array as Persons[3].

3) This statement shows you can print the entire content of the array. The output will list all the persons in the array. In our example, we have 4 persons in the array.

3. Run The Example

Running the example in chrome browser is below:

JavaScript Array Example - Output
JavaScript Array Example – Output

The first part shows picking a specific array cell and printing a specific person’s name. In the second part of the output, the entire array content is printed out in the html document.

4. Code Reference

Categories: JavaScript

Tags: ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.