What is an array?
An array
is an ordered list of items. These items can be anything valid to the JavaScript
language. Though, it is common to group similar content together (atleast outside of programming exercises). In my experience I have seen an array
of strings, numbers, and even other arrays (multidimensional arrays)
Arrays are objects
Because almost everything in JavaScript
is an Object
(thanks to the inheritance in object-oriented programming), arrays have properties
and methods
- which are of course just another name for variables
and functions
that are scoped to an Object
.
A discussion of array
methods is outside the scope of this blog post, but you can find more information in the resources section.
One such property we will focus on is the length
property. As you will see when we discuss for
loops, it is useful to know the length
of the array
you are looping over as it prevents exceeding the length of the list, similar to the off-by-one error.
Indexed arrays
Remember how I said arrays are ordered lists? Well instead of starting at 1, we start counting at 0. Because an array
is 0-indexed, you start counting at 0. So the first array
item is at position (sometimes called index) 0.
This is a very important concept, as it prevents a common error called off-by-one. This happens when you start counting at 1 and access the wrong (or nonexistent) index!
Speaking of indexes, we access array
elements using bracket syntax. For example:
let ages = [35, 25, 12];
let wrongSecondAge = ages[2]; // using bracket syntax, wrongly accessing the second element of the array... if you started counting at 1
console.log(wrongSecondAge); // 12... Should have started counting at 0
let lastAge = ages[ages.length - 1]; // dynamically get the last element of the array!
Using the example above, If getting the first array
element is as simple as ages[0]
, and the second is ages[1]
, how do we access the last item in an array. Since we know ages
has a length of 3, confirmed by console.log(ages.length);
, how about console.log(ages[3]);
?
Well, that works for as long as the array
only has 3 elements. What happens if you add items to the array? The index of 3 would no longer be accurate! surely there’s a dynamic way.
As you saw in the previous example, there’s a way to dynamically get the last item. So no matter how your array
grows or shrinks, you can ensure you’re accessing the last array item.
Using bracket syntax- ages[ages.length - 1]
- we tell JavaScript
to access the length
property on the array and find the last index, by starting the count from the end (-1).
What is a loop?
Loops are used to repeat a task a number of times. A common use- in older JavaScript
at least, as there are now array methods
to do this- is to use a for
loop to access array elements. But like anything in programming, we must understand the syntax so we can get the result we want.
The humble for loop
A for
loop is a type of function
used to repeat a piece of code x amount of times. It has three optional parts, though I haven’t found a use case to omit any of them. To understand the syntax let’s use a trivial example: logging the numbers 0 through 4 to the console
. The syntax for a for
loop looks like this:
for (let i = 0; i < 5; i++) {
console.log(i); // 0,1,2,3,4
}
Don’t let it intimidate you. The for
loop has 3 parts:
The initializer:
let i = 0;
start counting the looping from 0; *note: the variablei
can be named anything, buti
andj
seem to be common, albeit confusing, industry processes. Wouldstart
be a better variable name?*
The condition:
i < 5;
Tells the for loop the amount of times to run. It runs until this condition evaluates to false. The condition is evaluated before each iteration.
The iterator: Specify how the loop control variable (
i
) should change with each iteration. It is common to increment or decrement this variable depending on your needs.
Looping over an array using a for
loop
let nums = [
[4,3,2,1]
];
function addNums(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
console.log(arr[i][j]); // 4,3,2,1
sum += arr[i][j]; // equivalent to sum = 0 + arr[i][j];
}
}
return sum;
}
console.log( addNums(nums) ); // 10
Did you notice the nested for
loop? Due to the multidimensional structure of the nums
array
, I needed a way to first loop over the top-level array
, and then access the second (nested) array
.
Anything inside of the for
loop is ran i
amount of times. The second condition ensures the code will loop over the entire array, and not exceeding its length (this would cause an error).
The inner for
loop iterates over the innermost array
of numbers. Notice the use of two pairs of brackets arr[i][j]
to access the current number, with i
and j
representing the topmost array
and innermost array
respectively.
Then we add the numbers, creating a final value (10) when the loop is over. Finally we return that value -referenced by the sum
variable.
What do you think, is the for
loop syntax too complicated? When have you used a for
loop in your code?
Resources
Modern ways to loop over an array. JavaScript array methods