JS: Arrays
Theory: Modification
The primitive data types we studied so far are impossible to change. Any functions and methods over them return new values, but cannot do anything with the old ones.
This rule does not work with arrays. Arrays can change: they can increase, decrease, or change index values. We'll check into all of these operations in the following.
Changing of array elements
The syntax for changing an array element is essentially the same as for accessing an array element. The only difference is the assignment:
The most unexpected thing in this code is a change of the constant. Constants in JavaScript are not exactly how we imagined them before. A constant can store only a reference to the data (we will discuss it in the following lessons), but not the data itself. This means that we can change the data, but not the link. Technically, this means that we cannot replace the entire value of a constant:
Adding an element to an array
The push() method adds an element to the end of an array:
The unshift() method adds an element to the beginning:
Sometimes the addition index is known immediately, and in such a case the addition works the same way as the change:
Deleting an element from an array
You can delete an element from an array using a special delete statement: delete arr[index].
An example:
This method has several disadvantages, coming from the features of the internal organization of JavaScript. For example, after such deletion, you may be surprised to see that an array size has not changed:
There are other features and consequences of using this operator, which we will not drill down now. We presented it only as an example and do not recommend to use it when coding. In general, reducing array size is a rather undesirable operation. We'll talk more about this during one of the following lessons.
Recommended programs
Completed
0 / 22

