Arrays
In this chapter, we will explore JavaScript arrays.
In JavaScript, you can use arrays for storing multiple values in a single variable.
We can describe an array as a unique variable capable of holding more than one value simultaneously.
There exist two syntaxes for generating an empty array:
let arr = new Array();
let arr = [];
The second syntax is used most of the time. You can add initial elements in the brackets, like this:
let cars = ["Mercedes", "BMW", "Toyota"];
console.log(cars[0]); // Mercedes
console.log(cars[1]); // BMW
console.log(cars[2]); // Toyota
You can also replace an element as follows:
cars[2] = 'Lexus'; // now ["Mercedes", "BMW", "Lexus"]
Either you can add a new one to the array, like this:
cars[3] = 'Dodge'; // now ["Mercedes", "BMW", "Lexus", "Dodge"]
The array length is the total count of the elements. Here is an example:
let cars = ["Mercedes", "BMW", "Toyota"]
console.log(cars.length); // 3
In case you are going to show the overall array, you may use console.log, like this:
An array is capable of storing any types of elements:
// mix of values
let arr = ['BMW', { sitename: 'Web'}, true, function () {
console.log('welcome');
}];
// get the object at index 1 and then show its name
console.log(arr[1].sitename); // Web
// get the function at index 3 and run it
arr[3](); // welcome
Arrays can be viewed as a special type of object. One of the most notable similarities is that arrays can end with a comma.
For instance:
let cars = [
"Mercedes",
"BMW",
"Dodge",
];
Methods¶
One of the most widespread uses of arrays is a queue. in computer science, it is known as an ordered assembly of elements that support the following two operations:
push - is used for appending an element to the end
shift - is used for getting an element from the beginning, advancing the queue. In consequence, the second element becomes the first.
Arrays support both of the above-mentioned operations, and it’s a widespread practice for developers.
You can use arrays for another practice as well. It’s data structure named stack, which supports two operations:
push - it’s aimed at adding an element to the end.
pop - is aimed at taking an element from the end.
In javascript, arrays work with as a queue and as a stack. With the help of arrays, you can add or remove elements to/from the beginning of the end.
Methods working with the end of an array¶
pop
This method is used for extracting and returning the last element of the array. For instance:
let cars = ["Mercedes", "BMW", "Dodge"];
console.log(cars.pop()); // remove "Dodge" and alert it
console.log(cars); // Mercedes, BMW
push
You can use this method for appending the element to the end of the array, like this:
let cars = ["Mercedes", "BMW"];
cars.push("Dodge");
console.log(cars); // Mercedes, BMW, Dodge
The calls cars.push(...) and cars[cars.length] = ... are equal.
Methods working with the beginning of the array¶
shift
This method is targeted at extracting and returning the first element of the array.
For example:
let cars = ["Mercedes", "BMW", "Dodge"];
console.log(cars.shift()); // remove Mercedes and alert it
console.log(cars); // BMW, Dodge
unshift
This one is used to add the element to the beginning of the array, as follows:
let cars = ["BMW", "Dodge"];
cars.unshift('Mercedes');
console.log(cars); // Mercedes, BMW, Dodge
With the help of methods push and unshift, you can simultaneously add different elements.
Let’s have a look at this example:
let cars = ["Mercedes"];
cars.push("BMW", "Dodge");
cars.unshift("Toyota", "Ferrari");
// ["Toyota", "Ferrari", "Mercedes", "BMW", "Dodge"]
console.log(cars);
Internals¶
As we mentioned above, arrays are a special type of object. Square brackets can be used to access a property arr[0] come from the syntax of the object. One thing makes an array even more special. It’s their internal representation. The engine tends to store its elements consecutively in the contiguous memory area. But, note that they will break if you quit to work with the array in the given order and deal it as an ordinary object.
For example, it is technically possible to act like this:
let cars = []; // make an array
cars[99999] = 5; // assign a property with the index far greater than its length
cars.age = 25; // create a property with an arbitrary name
It is available because arrays are objects. You have the option of adding properties to them.
You should also know the cases of the array misuse to avoid them. Here are several examples:
- Adding a non-numeric property, such as arr.test = 9.
- Making holes, like add arr[0] and then arr[500] putting nothing between them.
- Filling the array in the reverse order. For example, arr[500], arr[499].
We can assume that one should treat arrays as unique structures working with them with the ordered data.
Loops¶
One of the common ways of cycling array items is the for loop over indexes.
Here is an example:
let arr = ["Mercedes", "BMW", "Dodge"];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Another form of loop is for..of.
The example looks like this:
let cars = ["Mercedes", "BMW", "Dodge"];
// iterates over array elements
for (let car of cars) {
console.log(car);
}
This form of the loop doesn’t give access to the number of the current element.
As arrays are objects, also you can technically use for..in:
let carsArray = ["Mercedes", "BMW", "Ferrari"];
for (let key in carsArray) {
console.log(carsArray[key]); // Mercedes, BMW, Ferrari
}
Anyway, it’s not a good idea, as it can cause potential problems, such as:
- The loop for..in may iterate over all the properties, not only the numeric properties.
- The loop for..in is optimized for generic objects but not arrays. That’s why it’s up to 10-100 times slower.
The Length¶
Whenever we modify the array, the length property automatically updates. It’s not the count of values in the array, but the numeric index + 1. For example, a single element with a large index will give a great length, like this:
let cars = [];
cars[100] = "BMW";
console.log(cars.length); // 101
Anyway, developers don’t use arrays in that way.
The length property is writable. When you decrease it, the array will be truncated. Let’s have a look at this example:
let arr = [1, 2, 3, 4, 5];
arr.length = 3; // truncate to 3 elements
console.log(arr); // [1, 2, 3]
arr.length = 5; // return length back
console.log(arr[4]); // undefined: the values do not return
You can easily clear the array by using arr.length = 0;.
Creating a New Array¶
Here is another syntax for creating an array:
let arr = new Array("Mercedes", "BMW", "etc");
Anyway, this syntax is not used frequently.
In case a new Array is called with just one argument, that is a number. After that, it creates an array without items, but with a particular length:
let arr = new Array(3); // will it create an array of [3]
console.log(arr[0]); // undefined! no elements.
console.log(arr.length); // length 3
In the code mentioned above, all elements are undefined .
Multidimensional Arrays¶
Arrays might have items that are arrays, as well. It can be used for multidimensional arrays to store matrices:
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][1]); // 5, the central element arrays
toString method¶
Arrays implement the toString method in their own way. It returns a comma-separated list of elements. Here is an example:
let arr = [1, 2, 3];
console.log(arr); // 1,2,3
console.log(String(arr) === '1,2,3'); // true
There is an alternative one, as well:
But they don’t have Symbol.toPrimitive and valueOf. Arrays implement merely the toString conversion. Thus, here [] transforms into "1" and [2,1] becomes "2,1".
If the binary plus "+" operator adds something to a string, it switches it to a string so that the next step looks as follows:
console.log("" + 1); // "1"
console.log("2" + 1); // "21"
console.log("2,2" + 1); // "2,21"
0 Comments
CAN FEEDBACK
Emoji