JavaScript Tutorial – Array

Arrays are used to store multiple values.

How to create array in JavaSCript

<script type="text/javascript">
   //array syntax
   var array-name = [item1, item2, ...]; 
</script>

Let’s see an example. An array of programming languages

<script type="text/javascript">
   var web = ["CSS", "HTML", "JavaScript", "PHP"]; 
</script>

In the above example, we created an array named web and it has 4 elements. JavaScript index start at 0. So the first element of the array is at index 0. You can then access the element of an array by index number.

How to access element of an array in JavaScript

<script type="text/javascript">
   var first = web[0]; //which is CSS
   var first = web[1]; //which is HTML
   var first = web[2]; //which is JavaScript
   var first = web[3]; //which is PHP
</script>
Try it yourself »

Array Length

length returns the number of elements in an array.

How to get length of an array

<script type="text/javascript">
   web.length;
</script>
Try it yourself »

Since array index starts at 0. length of a n array will always be one higher than the maximum index.

Add Element To An Array

How to add element to an array

<script type="text/javascript">
   web.push("XML"); 
</script>
Try it yourself »

New element will be added to the end of the array.