Array examples in JavaScript

We all know array is a special variable, which can hold more than one value right?. And you could have used array in server side languages such as Java, PHP, Dot Net etc., but you know you can also use array in client side script such as JavaScript.

First I will show how to define an array in JavaScript:

Defining array() is more or less same like any server side programming language.

Lets see how to add values in an array()

Now, an array is defined and values are added, lets see how to alert these values one by one, to do that we are going to loop through the array values:

Check the above code yourself, read the comments to know how the code is working.

So now you know how the array() is working in JavaScript, but if you see I have hard coded the values in the array, then how to add the values dynamically in an array()?.

You can add the values dynamically using push() function, lets see an example:

In the above example, basically I have added two buttons and created two function addAnArray() and alertArrayValues(), when you press the addAnArray(), it will push() a value to an existing array “myarr“, when you press alertArrayValues() it will alert all the values one by one.

See the demo here:




Related Posts

Leave a Reply