Javascript Array Tutorial - push method


In the previous article we saw how to add one element at the end of the array. Javascrupt provides another way of adding an element at the end using the push method. So the statement

x.push ('Ford';)

does the same thing as

x[3] = 'Ford';

or the

x[x.length] = 'Ford';

Here is the complete example


<html>
<body>

<script type="text/javascript">

var x = ['toyota','honda','Audi'];

x[x.length] = 'Ford';

for (i=0; i<=3; i++)
document.writeln('x['+i+'] = '+ x[i]+ '<br />');

</script>

</body>
</html>



You may like to try this example online here .

It gives the following output

x[0] = toyota
x[1] = honda
x[2] = Audi
x[3] = Ford
			

Advantage of the Push method

An advantage of the push method is that, you can add more than one element in a single statement. So, to add three cars at the emd, you could write.


x.push ('Ford', 'Hyundai','Volkswagon');


You may like to try this example online here .

So how do you add an item at the begining of an array ? Read in the next post.