There are plenty of reasons why we might want to count something in our code. We might want to apply CSS styles based on how many children an HTML element has, or we might want to do something to every object in a JavaScript array. Both counting objects and enumerating over objects is easy to accomplish in vanilla JavaScript without jQuery. Let's explore a few different ways we might want to count or enumerate.
Counting Things in JavaScript
Counting and enumeration are related, but counting is simpler in the sense that we're just checking the number of things present. Here are a few places counting might come up.
Getting the Length of an Array
Arrays are common and useful in JavaScript: you've almost certainly seen many of these comma-separated lists of values enclosed with square braces.
// Declare an array of strings
var array = [ 'john', 'paul', 'george', 'ringo' ];
Arrays have a built in property that you can drill down into to get the length of the array--that is, the number of values contained within the array. Just access Array.length
.
// Count an array's values using Array.length
var lengthOfArray = array.length;
console.log('Length of array:', lengthOfArray);
Counting an HTML Element's Children
We can get the number of children on an HTML element by first grabbing a reference to the node, and then checking its children.length
property. Here, children
is an HTMLCollection, but its length
value provides us with a child count similar to an Array.
// Grab the parent div
var element = document.getElementById('parent-div');
// Check how many children it has
var childCount = element.children.length;
console.log('child count:', childCount);
Counting an Object's Keys
One last thing you might want to count is a JavaScript object's keys. Keys are essentially the labels or IDs given to stored values; when we write a JavaScript object, the keys are to the left of colons separating them from their values.
const javaScriptObject = {
keyA: 'value',
keyB: 'value',
keyC: 'value'
}
In modern JavaScript environments, you can quickly count an object's keys with the help of a function.
// Grab a reference to our object
var obj = javaScriptObject;
// Use Object.keys() to get an array and access its length
var keysCount = Object.keys(obj).length;
console.log('keys count:', keysCount);
Enumerating Things in JavaScript
When we talk about enumeration, we're referring to the process of going through a collection of things, and performing an action in regards to each one of them. This happens a lot in code! You'll find yourself writing loops like the ones we're about to discuss quite frequently.
Enumerating with Array.forEach
One easy way to enumerate is with Array.forEach()
. This method will let us do something for each object in an array. Since the argument that forEach()
expects is the function we want to perform for each object, we might employ an arrow function to make things more concise.
// The argument should be the function we want to perform
// and each enumerated object is passed into that function
array.forEach((obj) => {
console.log(obj);
}
// We could also outsource the function...
var doSomething = (obj) => {
console.log(obj);
}
// ...and pass it into forEach() like a variable
array.forEach(doSomething);
Using Array.forEach()
is quite easy and logical, but it doesn't provide the same context that the for
keyword does.
Enumerating with For Loops
The for
keyword can be used to keep track of the index of the object that we're currently handling during the enumeration process. The syntax for a for
loop looks like this:
for (var i = 0; i < array.length; i++) {
// do something with array[i]
}
This syntax is just something that you'll commit to memory. Between the parentheses, there are three instructions separated by semicolons.
-
var i = 0
First, we initialize a variable. It's an integer thatfor
will use to report where we currently are positioned in the array we're enumerating over--that is, the index of our current position. -
i < array.length
This controls how long to run thefor
loop. In this example (a common use case), we've set the loop to run whilei
is less than the length of our array. The intention is to initializei
to 0 so that we start at the beginning of the array, then enumerate over it untili
is no longer less than the array's length, meaning we've touched every object in the array. -
i++
Finally, this instructs thefor
loop on how to change ouri
variable after finishing with each object.i++
increases our index value by 1 when we finish handling each object.
In between the for
loop's curly braces { }
we can put the block of code we want to run on each object in the array. The i
index variable is useful to us inside this block of code, because we can refer to the object within the array that we're currently handling using [i]
.
for (var i = 0; i < array.length; i++) {
// array[i] is the object we're currently handling
var obj = array[i];
// This will log every object of the array to the console
console.log(obj);
}
Wrap Up
These are just a handful of useful techniques to help you count and enumerate over objects when you need to. The for
loop in particular--or just the ability to recognize it--should prove useful as you learn. Hopefully with everything discussed above you see how easy counting and enumeration are in plain old vanilla JavaScript.
Top comments (2)
Another thing you can do is the for...of and for...in syntax such as:
Not sure if that's helpful or not :)
Love it! Never used either of these before. Thank you!