The Hidden side of out-of-the-box functions/features

Welike Amos
The Andela Way
Published in
7 min readNov 13, 2019
Image credit: unplash.com

Qn: Is writing JavaScript using the out-of-the-box functions any restricting?

To start off this few minute’s journey, which will be more of an adventure and discovery, we’ll deeply look into some of the commonly used out-of-the-box features that Javascript has. Do they enhance the efficiency of code or; would rather write a traditional for loop versus an out-of-the-box-feature function to suit their respective requirements? Reading this will get you asking yourself questions like, “why do we even have to get close to re-inventing the wheel? The for loop has no place in the modern-day Javascript development edge. Since ES5 was released, great new array functions were introduced to our dear JavaScript.” Oh yes! Phew, I may be right or wrong about imagining that you asked yourself that question, nonetheless, I have asked myself the same question and many others countless times. This has happened mostly when I’ve had to traverse through a big array of data before displaying it and I needed to select the iteration approach to employ.

The usage of loops is very common in software development, but as developers, we need to remember about proper implementation and avoiding nesting loops because it has a bad impact on the overall system performance. An example of a nested for loop is shown below;

Basic nested for loop

Also, in the case of a sister loop, the while loop, it’s important to pay attention to the condition which needs to be false at some point to not break the code or increase possible downtime of the application.

There are different ways to loop and iterate in JavaScript. Listing just a few; for, for…of, for…in, while, while and continue, and other out-of-the-box-feature methods which are similar to loops/iterators like arr.forEach, arr.values(), arr.keys(), arr.map(), arr.reducer(), etc.

We’ll use a case study of comparing forEach() function and the traditional for loop in Javascript when traversing an array. I’m using a Mac OS and Chrome for this illustration.

The Gist

But What Are Loops? Just for a better context, Loops play an essential role in software development, and they are used to iterate through arrays or other elements that are iterable. e.g Sets, Maps, Strings, etc.

Understanding and testing execution time for the for loop.

These three simple syntactic flavors are to help shed more light upon the quick syntax while using the for loop.

for (initialize; condition; increment);

for (initialize; condition; increment) single statement;

for (initialize; condition; increment) { multiple; statements; }

Open a javascript file in your preferred editor and name it forLoop.js. At this point, ensure that you have NodeJs installed. Please run this code with this command `node forLoop.js`. Just take note of the time difference displayed in the console. We’ll use it for comparison shortly. When I run it, this is what I get below;

looping through 1000 items with the for loop
This is what is printed in the console after looping a thousand items using the for loop

Understanding and testing the execution time for a simple forEach loop

The forEach is an Array method that we can use to execute a function on each element in an array. It’s a good example of an out-of-the-box function/feature. It can only be used on Arrays, Maps, and Sets. When using forEach , we simply have to specify a callback function. forEach calls a callbackfn once for each element present in the array, in ascending order. Given an array arr; the forEach syntax is shown below. For more details please visit here.

arr.forEach(callback(currentValue [,index [,array]])[,thisArg]);

Open a Javascript file in your preferred editor and name it forEachLoop.js. Please run this code with this command, node forEachLoop.js. Just take note of the time difference displayed in the console. As you can see in the code snippet below, the forEach() method also iterates through an array, but here we don’t specify a condition or updater, here we iterate through the given array, and we can return every item.

Looping over a thousand items using the forEach()
This is what is printed in the console after running the code above

You realize that forEach has a higher execution time on average of 10 runs. The time may differ each time you run the code, but the for loop average execution time after ten times is shorter. This implies that the traditional for loop will traverse an array with 1000 items in a much shorter time for a large number of requests from multiple users.

More comparison of the two array iterations in the chrome browser.

I continued to test both loops in a testing environment like the Google Chrome browser that runs several web applications with over 62.41% browser market share globally. For more details visit here.

I used snippets which are quick scripts that you can run on any page and have access to the page’s Javascript context. If you’re using Firefox, look out for Scratchpad. Using Snippets to help run both loops and display the respective time variations. Since chrome snippets provide a better testing environment, we are sure of a more realistic comparison.

Please copy the same code you used earlier in the editor of your choice and create two files that you’ll run and note the time differences. For emphasis, copy the code in the file named forEachLoop.js into a new snippet titled forEach.js. Also, copy the code in the editor file named forLoop.js into your new snippet titled forLoop.js. Note down the time difference after running each of the files respectively.

Below is a gif to illustrate the time variations between the two loops.

Gif Generated from the chrome browser Snippets

Quick Analysis of the Execution time for the two loops.

Quick Analysis on the average time between the two loops

Explanation

How can the newest and recommended solution make JavaScript so much slower? The cause of this pain comes from two main reasons, forEach and other functions like reduce() require a call-back function to be executed which is called recursively and bloats the stack, and additional operation and verification which are made over the executed code. For more details visit here and search for forEach or reduce.

Which One Should You Use?

The traditional for loop is the fastest, so you should always use that right? Not so fast-performance is not the only thing that matters. It is rare that you will ever need to loop over 1 million items in a frontend JS app at a go. Code Readability is usually more important, so default to the style that fits your application. If you prefer to write functional code, then forEach is ideal, while for-of is great otherwise. Fewer lines of code mean shorter development times and less maintenance overhead — optimize for developer-happiness first, then performance later.

Well, one may argue that at the end of the day, they’re relatively similar performance-wise. The only difference is your personal preference and some small case-by-case situations that may evolve later. I would say that don’t get too hung up on how you reach your solution. As long as you can solve the problem at hand, and also have a deeper insight like one you’ve just gained now into rightly applying out-of-the-box features versus the traditional loops, then you are better placed to know when and where to re-visit when you need to optimize performance with respect to the kind of application requirements and constraints present. This kind of insight is what every developer needs to have.

Lastly, for a small application, writing fast and more readable code is perfect — but for stressed servers and huge client-side applications, this might not be the best practice. In conclusion and to answer the question, “Is writing JavaScript using the out-of-the-box features any restricting”, I would say yes. But having deeper insight as you have just gained helps to curb all the restrictions.

Extra Tip

QN? What’s the preferred way to loop through objects in javascript? Objects not Arrays.

Oh yes, Javascript provides ways to loop over a set of objects as well. Plain objects aren’t iterable. The safe or easier way to iterate over properties is via a tool function like via objectEntries().

Illustrating this using for-in & for-of tricks. Just open a javascript file in your prefered editor and call it loop.js. Please run this code with node loop.js.

For-in_loop
for-in_Continued

The result looks like this below.

The result after looping over a javascript object

Happy hacking and thanks for reading!

--

--

Welike Amos
The Andela Way

As a keen student of life, Diligence with humility matter.