Javascript Array Example FAQ

Let us see how to declare a Javascript Array and use basic Javascript array functions and methods in this post, with examples. This tutorial on Javascript Arrays, is targetted towards beginners who are looking for some demonstration code in using the Array object.The tutorial is implemented as a How To kind, which can help you to be spot on with your Array concept needs. Here is a step by step learning FAQ for Javascript Arrays.

1) How to create a new array object in Javascript?

To create a new array Object in Javascript, use the sample code provided below
<script type="text/javascript">
var createArray=new Array();
</script>

2) How to find the array length of an Array object?

To find the length of an Array object in Javascript or to count the number of elements in an Array, you can use the "length" property. "Arrayobject.length" would help you to find the number of elements in a Javascript Array. For an empty Array, the number of elements is always 0.
var myArrayLength=createArray.length;

3) How to set the size of an Array, when declaring it?

To predefine the size of an Array at the time of creation, you can pass the size parameter as a number to the constructor. As an example, you can do as provided below
var createArray=new Array(200);
This example creates an array with a predefined length of 200. When you assign a value for the 200th array element, then the array resizes itself automatically and this does not throw an error.

4) After declaring, how to add elements to a Javascript Array?

To populate a Javascript Array by, you can just refer to the element number and push the required data into it. An example for entering data into a Javascript Array is provided below;
<script type="text/javascript">
var createArray=new Array(3);
createArray[0]='first element';
createArray[1]='Second element';
createArray[2]='Third element';
</script>

5) What are the different methods of entering data in a Javascript Array?

Apart from the approach given earlier, you can also push data into an Array by using the example code provided below; [ you need not refer to the array element in this method ]
<script type="text/javascript">
var createArray=new Array(3);
createArray[createArray.length]="first element";
createArray[createArray.length]="Second element";
createArray[createArray.length]="Third element";
</script>

If you know all the array parameters beforehand, you can directly create the array by using the code provided below;

var createArray=new Array("first element","Second element","Third element");

6) How to remove data from a Javascript Array?

You can use the DELETE method to delete an element from a Javascript Array. Removing an element from the array using this method, does not reduce the length of the array. To remove the third array element, you can use an example as provided below
delete createArray[2]; //deletes the second element from the Array, but the length of the array does not change

1 comment: