This article is on how to create array variable in Javascript following with an example to show how to do it. Javascript itself is knowned as a client-side scripting language where it is widely used. By writing this article, defining an array variable will be discussed and it will also be presented with an example to depict the output of the array variable itself.
First of all, there is a need to declare in the web page file using Javascript that there is a Javascript snippet code which is needed to be processed in that web page file. It is informing Web browser used to render and to process the web page file to interpret the Javascript snippet code.
The following is a self-declaration of Javascript snippet code file block definition :
<script type="text/javascript"> </script>
After defining Javascript client-side scripting block code as shown above, the next step is about defining or creating the array variable as shown below :
var array_variable = [];
The above definition is an empty array variable. It is a simple array literal definition which is only define a single empty array variable. Another way to simply define an empty array variable is by using array constructor definition. Below is the array constructor definition using ‘Array’ class construction by creating a new instance of array variable :
var array_variable= new Array();
Based on the reference search via search engine such as Google, there are slight difference on using array variable for both definition.
In term of array literal definition using [], it cannot specify the size directly. It is very useful for defining an array variable where the size of the array itself is going to be vary and it is flexible. On the other hand, the array construction definition using new Array(), where it is actually create an instance of array variable can be used to declare and initiate the size or the number of element which can be held. Below is an example to show the description above :
var array_variable = [5];
It is only declaring an array variable with a single element. The value of that single element contained in the array variable named ‘array_variable’ is 5. Try to compare it with the following definition of an array variable using array class construction through the creation of an array instance variable :
var array_variable = new Array(5);
It will definitely define a new array variable named ‘array_variable’ which has the element size of 5 element.
So, in order to assign values to an array variable, it can be done in the following ways :
var array_variable = ["Tom","Mike","John"];
or
var array_variable = new Array("Tom","Mike","John");
This is another reference found in other person’s blog description which can be visited in the following link.
One thought on “How to Create Array in Javascript with an Example”