Array Explanation for app.codility.com/programmers in JavaScript
Category of Article : Technology | Computers and Software | Algorithm
By: Chrysanthus Date Published: 2 May 2025
An array is a list structure that can be used to store many items in one place.
List Example
Imagine that you are a proprietor of a small company, and you have 10 employees. In your ECMAScript program, you can have their first names in an array. Each list item here is a first name. Let the list be: John, Mary, Peter, Augustine, Angela, Susan, Martin, Grace, Paul, Simon. These items can be placed in a special ECMAScript object called an array. An array item is called an element.
Creating an Array
The ECMAScript global object has a number of properties. One of theses properties is called, Array. It is a function (method). It is also a constructor, meaning it is used to create arrays. Remember, in ECMAScript, a function is also an object.
There are two ways of creating an array: you either use the constructor, Array() in a new expression or you call the constructor as a function.
Creation with new Expression
The syntaxes to create an array with the new expression are as follows:
arrayObject = new Array()
This is for an empty array object, where arrayObject is the array object identifier, new is the new operator, and Array() is the constructor.
arrayObject = new Array(int)
This is when you are giving the array an initial length, which is the number of values (elements). You have to replace int with the length integer (whole number) in your code.
arrayObject = new Array(value0, value1, value2, . . .)
This is the case when you type the values of the array as you create the array. Each such value represents an element. If a value is a string, you type the value in quotes. If the value is a number, you type the number without quotes.
Creation as Function
The syntaxes to create an array, calling the constructor as a function are as follows:
arrayObject = Array()
This is for an empty array object, where arrayObject is the array object identifier, and Array() is the constructor.
arrayObject = Array(int)
This is when you are giving the array an initial length, which is the number of values (elements). You have to replace int with the length integer (whole number) in your code.
arrayObject = Array(value0, value1, value2, . . .)
This is the case when you type the values of the array as you create the array. Each such value represents an element. If a value is a string, you type the value in quotes. If the value is a number, you type the number without quotes.
Array Initializer
You can create array by literal notation, i.e:
arrayObject = [value0, value1, value2, . . .]
Note the use of the square brackets.
Array Indices
The value of an array can be addressed using integers (whole numbers). These integers are called indices (singular is index). The syntax to access an array value (element) is:
arrayObject[index]
where arrayObject is the array identifier and index is an integer beginning from zero. Counting of array elements (values) begin from zero, not 1. You count as follows: 0, 1, 2, 3, 4, etc.
Reading Array Values
To read the value at position 3 of an array, you have to use the index, 2, since index counting begins from zero, not 1. You always have to subtract the value of 1 from the position to get the index. So, to read the value of an array at position, 3 you would type something like:
valRead = arr[2];
Here, arr is the array identifier and 2 is the index. Note the use of the square brackets. The value is read and assigned to the identifier, valRead, which is a name of your choice. You can also type the integer (2 for example), in quotes.
Giving Values to an Array
You can give values to an array during creation or you can give the values using the bracket notation (square brackets). The following statement shows how you would create an array of the above list, using the new expression and giving values at the same time:
arr = new Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon");
Here, arr is the identifier of the array; it is a name of your choice. The following statement shows how you would create an array of the above list, using the constructor as a function and giving values at the same time:
arr = Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon");
The other way of giving value is by the bracket notation. For this you create an empty array first, with or without the initial intended number of elements. Then you assign values beginning from index zero. The following code segment illustrates this:
arr = new Array(); arr[0] = "John"; arr[1] = "Mary"; arr[2] = "Peter"; arr[3] = "Angela";
The index number is always 1 less than the position number.
Changing the Value of an Array Element
To change the value of an array element, use the bracket notation. If you want to change the value at position 2 of the arr array above, from “Mary” to “Beyonce”, you would type a new line in the script as follows:
arr[1] = "Beyonce";
It is that simple, just reassign a new value below the created array in the script.
Displaying Array Content
You can display the array values one-by-one, or you can display them all in one sweep. To display an array value, you can type something like,
alert(arr[2])
for index 2, position 3 (for the alert box);
or
document.write(arr[2])
If the value is assign to an identifier as in,
valRead = arr[2];
then you can use the identifier as the argument for the alert() or write() function.
To display all the values of the array, use the array identifier without the square brackets as argument to the display function.
Iterating over an Array
The do-while-loop
The following scriptshows a do-while-loop in JavaScript :
<script type='text/javascript'> "use strict"; const arr = ["bread", "butter", "cheese"]; //array of strings let i = 0; do { document.write(arr[i] + '<br>'); i = i + 1; //increment: add 1 } while (i < 3); </script>
The output consists of each of the array elements, beginning from the first, then second and then third.
The do-while-loop has a block, delimited by curly brackets (braces). The "do" reserved word is in front of this block. The loop uses a variable, i that is incremented for each pass, through the block.
The statements in the block are executed over and over, in the order typed. The while-condition is that, the block should stop executing, when the value of i is just below 3, that is 2. The first statement in the block prints out an array value. The second statement increments i (adds 1). The block is executed 3 times; when i is 0; i is 1; and i is 2. i was initialized to 1, in front of the do-while-loop.
With the do-while-loop, the block is executed before the while-condition is checked. Note that the do-while-loop construct ends with a semicolon, just after the while-condition "(i<3)".
The While-Loop
The while-loop is similar to the do-while-loop. With the while-loop, the while-condition is checked before the loop body (block) is executed, for each iteration. With the do-while-loop above, the body is executed first, before the while-condition is checked, for each iteration. The following while-loop code segment would replace the above do-while-loop code segment (would do the same thing):
const arr = ["bread", "butter", "cheese"]; //array of strings let i = 0; while (i < 3) { document.write(arr[i] + '<br>'); i += 1; //increment: add 1 }
Note that the while-loop construct does not end with a semicolon after, '}'. Also note the alternative increment statement, "i += 1;", which is the same as "i = i + 1;"
The for-Loop
The while-loop has a difference with the do-while-loop. The for-loop is another way of coding the while-loop. The above while-loop code segment would be coded with the for-loop as follows:
<script type='text/javascript'> "use strict"; const arr = ["bread", "butter", "cheese"]; //array of strings for (let i = 0; i < 3; i += 1) { document.write(arr[i] + '<br>'); } </script>
The for-loop begins with the reserved word, "for" with all letters in lowercase. Then there is the parentheses. In the parentheses, there are three statements, with the last one not ending with a semicolon. The last statement is the increment statement, which has been transferred from the body of the while-loop, to this position. The middle statement is the while-condition. The first statement is the initialization of i to 0; it is no longer outside the construct. There is now only one statement in the body of this loop (for-loop). The output here, is the same as in the previous cases.
Other Script Examples
In the following script, an array for the list above is created by calling the array constructor as a function, with all the values given as argument. One of the values in the array is displayed.
<script type='text/javascript'> "use strict"; let arr = Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon"); let indxIdent = arr[4]; document.write(indxIdent); </script>
The extra HTML code is to produce a web page. The output is "Angela" of index 4, position 5. Always subtract 1 from the position to have the index. You should try the above code.
In the following script, an array for the list above is created with the constructor in the new expression, without giving the values. Some values at certain positions are then given. The initial length of the array is 10. The whole array is then displayed.
<script type='text/javascript'> "use strict"; let empArr = new Array(10); empArr[0] = "John"; empArr[2] = "Peter"; empArr[4] = "Angela"; empArr[6] = "Martin"; document.write(empArr); </script>
The output is:
John,,Peter,,Angela,,Martin,,,
Note: you can type the index within single or double quotes, so
empArr["2"] = "Peter";
is alright.
Adding Values to an Array
To add a value you can use the bracket notation. If you make a mistake and use an index that is already in the array, you would end up changing the value of that index. For example, if in the above array, where there are 10 elements (and some values do not exist), and you add a value, using index 4, you will change the value of index 4 which is "Angela" at the moment. If for an element whose value does not exist, you give the element a new value, you will have a new value for that element. Adding a value for index 3 above, will give index 3 a new value.
To add an element (value) successfully, you have to use an index that is higher than that of the array highest index. For the above array, since there are 10 elements, it means that highest current index is 9. With that you can add an element with index, 10, or 11, or 12, or 13, etc. If you add an element with an index that is higher than the current highest index plus 1 (e.g. 18 for the above list), you end up with the added element and elements with values that do not exist, whose indices are between that which you have just added and the previous highest index.
In the following code of initially 10 elements, an element (value) has been added at index 12. The resulting whole array is displayed.
<script type='text/javascript'> "use strict"; let empArr = new Array(10); empArr[0] = "John"; empArr[2] = "Peter"; empArr[4] = "Angela"; empArr[6] = "Martin"; empArr[12] = "Victoria"; document.write(empArr); </script>
The output is:
John,,Peter,,Angela,,Martin,,,,,,Victoria
Note on Initial Array Length
When creating an array, either by calling the constructor as a function or by having the constructor in the new expression, if there is only one argument, and that argument is an integer (whole number), then that argument is the initial length of the array, otherwise, the argument should be the only value (element) of the array. So, in the statement:
arr = new Array("plate");
“plate” is the only value of the array and in the statement:
arr = new Array(5);
the array has five elements, each with a value that does not exist.
The length Property
Whether a constructor is executed as a new expression or is called as a function, if there is only one argument, and if the argument is an integer (whole number) then that integer is the initial length of the created array. This length can still increase if you add more elements. You can still create an array without giving it an initial length. As you add elements to the array, the length increases, from zero.
The length property is used to know the length of a created array. The syntax is:
arrayObject.length
This expression returns the length of the array. The following code shows this in action:
<script type='text/javascript'> "use strict"; let cutlery = new Array(); cutlery[0] = "spoon"; cutlery[1] = "knife"; cutlery[2] = "fork"; let len = cutlery.length; alert(len); </script>
In the code the expression, "cutlery.length" obtains the length of the object, cutlery and assigns it to the identifier, len.
Value as Number
When the value of an array element is a number, type the number without quotes. The following example illustrates this:
ages = new Array(12, 15.5, 16);
Array Literal
Note: you can also create an empty array as follows:
arr = [];
where arr is a name of your choice. Or you can create an array with elements as follows:
ages = [12, 15.5, 16];
Adding and Removing Elements in JavaScript
The shift() Method
This method removes the first element of the array and returns the element, shortening the array by one element. Re-indexing takes place, i.e. index 1 becomes index 0, index 2 becomes index 1, etc. The syntax is:
arrayObject.shift ()
The method returns the shifted value, or undefined if array is empty.
Read and try the following code that illustrates the use of the shift() method:
<script type='text/javascript'> "use strict"; let arr = new Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon"); let val = arr.shift(); alert(val); document.write(arr); </script>
Note that there is no unnecessary comma to indicate the absense of a value.
The unshift() Method
This method prepends one or more elements to the front of the array. The elements in the incoming argument list are fitted in the order in which they are inputted. The length of the resulting array increases. Re-indexing takes place, i.e. index 0 may become index 1, index 1 may become index 2, etc. The syntax is:
arrayObject.unshift ( [ item1 [ , item2 [ , … ] ] ] )
where the parameters form the list of elements to be inputted.
The method returns the new number (length) of elements in the array. Read and test the following code:
<script type='text/javascript'> "use strict"; let tools = new Array("Hammer", "screw driver"); let len = tools.unshift("saw", "pincer"); document.write(tools); alert(len); </script>
The pop() Method
This method removes the last element of an array and returns the value, shortening the array by one element. The syntax is:
arrayObject.pop ()
The method returns the last value of the array. If array is empty, undefined is returned. Read and try the following code:
<script type='text/javascript'> "use strict"; let arr = new Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon"); let val = arr.pop(); alert(val); document.write(arr); </script>
The push() Method
This method adds one or more elements to the end of the array. The length of the array increases. The syntax is:
arrayObject.push ( [ item1 [ , item2 [ , … ] ] ] )
where the parameters form the list of elements to be added. The function returns the new number (length) of elements in the array. Read and try the following code:
<script type='text/javascript'> "use strict"; let tools = new Array("saw", "pincer"); let len = tools.push("Hammer", "screw driver"); document.write(tools); alert(len); </script>
The slice() Method
This method reads and returns a sequence of elements in the array. The return entity is an array, the slice. The original array remains unchanged. Read and try the following code:
<script type='text/javascript'> "use strict"; let arr = new Array("AA", "BB", "CC", "DD", "EE", "FF", "GG"); let ret = arr.slice(2, 5); document.write(ret); document.write('<br>'); document.write(arr); </script>
Note that the original array remains unchanged. The syntax of the slice() method is:
arrayObject.slice (start, end)
arrayObject is the original array. The slice method takes two arguments, start and end, and returns an array containing the elements of the original array from start element up to, but not including, end element (or through to the end of the array if end is absent).
The splice() Method
The slice() method only copies the sequence of elements and leaves the original array unchanged. However, the splice() method removes the sequence of elements and can replace the sequence with a longer or shorter new sequence. After removing the sequence, the method can even replace it with nothing. The syntax of the method is:
arrayObject.splice (start, deleteCount [ , item1 [ , item2 [ , … ] ] ] )
where arrayObject is the original array. start is the index at which the method starts removing elements. deleteCount is the number of elements to be removed. The elements for replacement, if any are typed after that
The method returns an array consisting of the removed elements.
Read and test the following code:<script type='text/javascript'> "use strict"; let arr = new Array("AA", "BB", "CC", "DD", "EE", "FF", "GG"); let ret = arr.splice(2, 3, "PP", "QQ"); document.write(ret); document.write('<br>'); document.write(arr); </script>
JavaScript Array Data Methods
The sort Method
If the values of an array consist of strings, this method will sort them alphabetically. In this case, there will be re-indexing; that is the indexing will change and the new string values will have new indexes beginning from zero. The method returns the sorted array; the original array is also sorted. Read and test the following code:
<script type='text/javascript'> "use strict"; const fruits = new Array("pear", "orange", "strawberry", "lime", "lemon", "avocado", "guava", "banana"); fruits.sort(); document.write(fruits); </script>
The extra HTML code is to produce a web page. The output is:
avocado,banana,guava,lemon,lime,orange,pear,strawberry
sorted alphabetically. In the code, the returned array has not been assigned to any identifier. The syntax for the sort method is
arrayObject.sort (comparefn)
The comparefn parameter is optional. If the values of the array are made up of, strings and numbers or only numbers, then you will need the comparefn parameter. comparefn stands for “compare function”. It is a function that will be used to compare the values. However, I will not go into that in this tutorial.
The reverse Method
This method is used to reverse the order of values in an array. The values of the original array are reversed. If you assigned the method expression to an identifier, the original reversed array will be returned to the identifier. The syntax is:
arrayObject.reverse()
Read and try the following code:
<script type='text/javascript'> "use strict"; const empArr = new Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon"); empArr.reverse(); document.write(empArr); </script>The output is:
Simon,Paul,Grace,Martin,Susan,Angela,Augustine,Peter,Mary,John
reversed.
The indexOf Method
This method can take as argument the value of an element in the array, and then return the index of the element (value). Read and try the following code:
<script type='text/javascript'> "use strict"; const empArr = new Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon"); let inter = empArr.indexOf("Grace"); alert(inter); </script>
The return integer (whole number) is 7, for the value "Grace". The indexOf method is case sensitive, meaning, if the search string is "Grace", it will look for "Grace" and not "grace". The syntax of the method is:
arrayObject.indexOf ( searchElement [ , fromIndex ] )
where the second argument is optional as can be deduced from the square brackets. The first argument, searchElement is for the value in the array to be searched. When the value is seen, the index is returned. If the value is not seen, -1 is returned. If the array has more than one of the same values, the first index is returned.
If you want the search to begin from a particular position in the array, then type the index for the second argument, where you want the search to begin. In the absence of the second argument, zero is assumed for searching the whole array. So, the default value for fromIndex is 0. If this value is greater than or equal to the length of the array, -1 is returned and the array is not searched.
The lastIndexOf Method
The lastIndexOf is the opposite of the indexOf method. If there is more than one element of the same value, then the last index is return. If there is only one element, the index is still returned as with the indexOf method. The syntax is:
arrayObject.lastIndexOf ( searchElement [ , fromIndex ] )
Here, searchElement has the same meaning as for indexOf. However, the search here is backwards (from highest index to lowest index). If you want the search to begin from a particular position in the array, then type the index for the second argument, where you want the search to begin (and go backwards). In the absence of the second argument, the length minus 1 is assumed as index for searching the whole array. So, the default value for fromIndex here, is length-minus-1. If this value is greater than or equal to the length of the array, the whole array is searched. Read and try the following code:
<script type='text/javascript'> "use strict"; const fruits = new Array("pear", "orange", "strawberry", "lime", "lemon", "avocado", "lime", "guava", "banana"); let inter = fruits.lastIndexOf ("lime"); alert(inter); </script>The output is 6, the last index for “lime” which occurs twice.
The concat Method
You can form a new array by appending a number of elements to an existing array, in the order in which the elements are typed. The syntax is:
arrayObject.concat ( [ item1 [ , item2 [ , … ] ] ] )
The array is arrayObject. The values to append to the array are item1, item2, item3, etc. The items are all optional as indicated by the square brackets. It is the returned array that has both lists, the original array remains unchanged. Read and try the following code:
<script type='text/javascript'> "use strict"; const fruits = new Array("AA", "BB", "CC", "DD", "EE", "FF"); let newArr =fruits.concat("GG", "HH", "FF"); document.write(newArr); </script> The output is:AA,BB,CC,DD,EE,FF,GG,HH,II
The join Method
You can join all the values in an array into a string. The syntax is:
arrayObject.join (separator)
The argument, separator is what will separate the values in the string. It can be a comma, space, hyphen, etc. It is of your choice. Read and try the following code where the separator is a space:
<script type='text/javascript'> "use strict"; const arr = new Array("United", "Nations", "Educational", "Scientific", "Cultural", "Organization"); let str = arr.join(' '); document.write(str); </script>
The output is:
United Nations Educational Scientific Cultural Organization
In the code, the separator is typed in quotes. So a comma would be typed as ',', a space would be typed as ' ' and a hyphen would be typed as '-'. The separator argument is optional. In its absence, a comma is assumed. So the comma is the default separator.