Broad Network


Creating and Using Arrays in ECMAScript 2015

The ECMAScript Array – Part 1

ECMAScript 6

Foreword: In this part of the series. I explain how to create and use arrays in ECMAScript.

By: Chrysanthus Date Published: 14 Jul 2016

Introduction

This is part 1 of my series, The ECMAScript Array. In this part of the series. I explain how to create and use arrays in ECMAScript.

Pre-Knowledge
Every computer language builds up. You need to learn something today in the language, and then use it to learn something at a higher level in the same language, tomorrow. This series is part of my volume, ECMAScript Course. At the bottom of this page, you have links to the different series you should have studied before reaching here.

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.

Script Example
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.

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

    <script type="text/ECMAScript">

        arr = Array("John", "Mary", "Peter", "Augustine", "Angela", "Susan", "Martin", "Grace", "Paul", "Simon");

        indxIdent = arr[4];

        document.write(indxIdent);
        
    </script>

</body>
</html>

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/ECMAScript">

        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,,,

When you use the array identifier for the display function, all the values are displayed separated by commas, in a line. A value that does not exist is not displayed; if a comma was to be typed after it, it is typed.

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 still 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/ECMAScript">

        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/ECMAScript">

        cutlery = new Array();

        cutlery[0] = "spoon";
        cutlery[1] = "knife";
        cutlery[2] = "fork";

        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];

With that we come to the end of this part of the series. See you in the next part.

Chrys

Related Links

ECMAScript Basics
ECMAScript Operators
Expressions in ECMAScript
Statements in ECMAScript
Custom Objects in ECMAScript
Functions in ECMAScript
ECMAScript Date Object
The ECMAScript String Object
ECMAScript String Regular Expressions
ECMAScript Template Literal
The ECMAScript Array
ECMAScript Sets and Maps
ECMAScript Number
Scopes in ECMAScript
Mastering the ECMAScript (JavaScript) eval Function
Sending Email with ECMAScript
ECMAScript Insecurities and Prevention
Advanced Course
Advanced ECMAScript Regular Expressions
Promise in ECMAScript 2015
Generator in ECMAScript 2015
ECMAScript Module
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course

NEXT

Comments

Become the Writer's Follower
Send the Writer a Message