Javascript Array Tutorial - unshift method


Let us say we have an array of 3 elements

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

Now we want to add three elements at the begining of the array. Basically the array should look like

x = ['Ford', 'Hyundai','Volkswagon','toyota','honda','Audi'] ;

We could potentially use the assignment operations which would make the things complex. Fortunately, javascript provides an easy unshift method. Here is what you can do to add elements at the begining.

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

Here is the complete example


<html>
<body>

<script type="text/javascript">

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

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

for (i=0; i<=5; 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] = Ford
x[1] = Hyundai
x[2] = Volkswagon
x[3] = toyota
x[4] = honda
x[5] = Audi
			

You may like to try this example online here .