Array stores multiple values.
There are couple of ways to initialize array:
In this example an array with 3 elements is created.
Size is the count of elements in array.
It's accessed via the length
property.
Output:
Array's values can be accessed via indexes starting from 0.
If we declare the following array:
It's elements are:
So if we type the following line:
It will print:
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:
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.
Elements can be inserted using the push
function.
Let's have a program which fills array with values:
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.