DEV Community

Cover image for Counting and Enumerating Over Things with Vanilla JavaScript
Nathan Pasko
Nathan Pasko

Posted on • Updated on

Counting and Enumerating Over Things with Vanilla JavaScript

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' ];
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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]
}
Enter fullscreen mode Exit fullscreen mode

This syntax is just something that you'll commit to memory. Between the parentheses, there are three instructions separated by semicolons.

  1. var i = 0 First, we initialize a variable. It's an integer that for will use to report where we currently are positioned in the array we're enumerating over--that is, the index of our current position.
  2. i < array.length This controls how long to run the for loop. In this example (a common use case), we've set the loop to run while i is less than the length of our array. The intention is to initialize i to 0 so that we start at the beginning of the array, then enumerate over it until i is no longer less than the array's length, meaning we've touched every object in the array.
  3. i++ Finally, this instructs the for loop on how to change our i 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);
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
gv14982 profile image
Graham Vasquez

Another thing you can do is the for...of and for...in syntax such as:

// for...of is used for enumerating over arrays
let arr = [ 1, 2, 3 ];

for (const num of arr) {
  console.log(num);
}

// Would print out 1 then 2 then 3

// for...in is used for enumerating over objects

let obj = { a: 1, b: 2, c: 3 };

for (const key in obj) {
  console.log(obj[key]);
}

// Would print out 1 then 2 then 3
Enter fullscreen mode Exit fullscreen mode

Not sure if that's helpful or not :)

Collapse
 
sprite421 profile image
Nathan Pasko

Love it! Never used either of these before. Thank you!