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:
1 |
var TheNumbers = new Array(); |
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:
1 |
Var TheNumbers = []; |
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]
.
1 |
var theNumbers = [1,2,3,4]; |
2. JavaScript One Dimensional Array Example
Now look at the example below:

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:

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:

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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html lang="en"> <head> <title>Number Conversion</title> </head> <body> <script> //Sample 01: Create an Array var Persons = ["Person 1", "Person 2", "Person 3"]; Persons[3] = "Person 4"; //Sample 02: Now Read Array & Print Name document.writeln("<h3>First Element of Array :" + Persons[0] + "</h3>"); document.writeln("<h3>Fourth Element of Array :" + Persons[3] + "</h3>"); //Sample 03: Print Entire Array document.writeln("<h3>Full Array is :-</h3>"); document.writeln(Persons); </script> </body> </html> |
Categories: JavaScript