JS: Arrays
Theory: Syntax
An array in programming is any ordered set (or collection) of elements, whether they are courses on Hexlet, students in a group or friends on your favorite social network. The role of an array is to present such collections as a single structure, allowing you to work with them as a whole.
Array definition
In the example, the array ['cats', 'dogs', 'birds'] is defined, which is then assigned to the constant animals.
Pay attention to the names of constants containing arrays. They are plurals. This highlights the constant's nature and makes the code easier to analyse.
Getting data
Elements in the array are ordered from left to right. Each element has an ordinal number called an index. The array's indexing starts from zero. So the first element is available by index 0, the second by index 1, and so on. To extract an element by index from an array, a special syntax is used:
You can find out the size of an array by accessing its length property.
In real-world tasks, the index is often calculated dynamically, so specific elements are accessed using variables:
And even like this:
Such a call is possible for one simple reason; an expression is expected inside the brackets, and where an expression is expected, you can substitute everything that is calculated. Including the function call:
Quite often when working with arrays you need to get the last element. To do this, just calculate the last index of the array using the formula array_size - 1, by which you can refer to the last element:
at()
Another way to work with indexes is the at() method. It was added to be able to specify negative indexes, it allows you to take elements from the end without calculating indexes, like in the example above:
Recommended programs
Completed
0 / 22

