Arrays

Array stores multiple values.

Initialization

There are couple of ways to initialize array:

Empty array

Initial values

In this example an array with 3 elements is created.

Size

Size is the count of elements in array.

It's accessed via the length property.

Output:

Accessing values

Array's values can be accessed via indexes starting from 0.

If we declare the following array:

It's elements are:

array-indexing

So if we type the following line:

It will print:

Index out of Bounds

Accessing index outside of the array results in undefined value

Let's have an array with 4 elements. If we access the 4th or higher index undefined will be returned.

Such example is:

Output:

Printing All Elements

Let's have an example in which all elements of array are printed.

Output:

Other way to do it is via the forEach.

Notice that forEach is not supported by the older browsers such as Internet Explorer.

Inserting Elements

Elements can be inserted using the push function.

Let's have a program which fills array with values:

Product Of Elements

Let's have a program which calculates the product of all even numbers:

Output:

The only even numbers in the array are 2 and 4 which are multiplied.