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

To start off this few minutes’ 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;

for (let y = 0; y < 2; y++){
  for (let x = 4; x < 6; x++){
    console.log(x, y);}
}

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, forof, 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? For 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;

// for loop
var counter = 1000;
var t0 = Date.now();
for (let i = 0; i < counter; i++) {
console.log('This is a for loop');
}
var t1 = Date.now();
console.log('for loop…time ' + (t1 - t0) + ' milliseconds.');
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 callback function 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.

// forEach function
var array = Array.from(Array(1000).keys(), n => n + 1);
var t0 = Date.now();
array.forEach((item, index) => {
console.log('This is the forEach loop');
});
var t1 = Date.now();
console.log('forEach()…time ' + (t1 - t0) + ' milliseconds.');
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.

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.

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 forloop is the fastest, so you should always use that right? No, because 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 preferred 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.

// Use a For-In Loop
const equine = { horse: '🐴', zebra: '🦓', unicorn: '🦄'}
for (const key in equine) {
   if (equine.hasOwnProperty(key)) {
       console.log('>',equine[key]);
   }
}
// Unwrap the the Values
for (const val of Object.values(equine)) {
   console.log('1',val);
}
// Create a Map
const equineq = new Map(Object.entries(equine));
for (const v of equineq.values()) {
   console.log('2',v)
}
For-in_loop

The result looks like this below:

Happy hacking and thanks for reading!

featured_image
About the Author

Welike Amos

Thanks for subscribing!

 

More Insights

November 8, 2019

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

Welike Amos

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

To start off this few minutes’ 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;

for (let y = 0; y < 2; y++){
  for (let x = 4; x < 6; x++){
    console.log(x, y);}
}

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, forof, 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? For 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;

// for loop
var counter = 1000;
var t0 = Date.now();
for (let i = 0; i < counter; i++) {
console.log('This is a for loop');
}
var t1 = Date.now();
console.log('for loop…time ' + (t1 - t0) + ' milliseconds.');
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 callback function 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.

// forEach function
var array = Array.from(Array(1000).keys(), n => n + 1);
var t0 = Date.now();
array.forEach((item, index) => {
console.log('This is the forEach loop');
});
var t1 = Date.now();
console.log('forEach()…time ' + (t1 - t0) + ' milliseconds.');
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.

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.

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 forloop is the fastest, so you should always use that right? No, because 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 preferred 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.

// Use a For-In Loop
const equine = { horse: '🐴', zebra: '🦓', unicorn: '🦄'}
for (const key in equine) {
   if (equine.hasOwnProperty(key)) {
       console.log('>',equine[key]);
   }
}
// Unwrap the the Values
for (const val of Object.values(equine)) {
   console.log('1',val);
}
// Create a Map
const equineq = new Map(Object.entries(equine));
for (const v of equineq.values()) {
   console.log('2',v)
}
For-in_loop

The result looks like this below:

Happy hacking and thanks for reading!

featured_image
About the Author

Welike Amos

Thanks for subscribing!

 

More Insights

Talks At Andela: Building Engineering Teams at Scale

What does “building engineering teams at scale” mean to you (as an engineer or team lead) and yo...

19_February_2020

How to Build a CRUD App in Vanilla PHP

Introduction During a recent technical assessment, I was tasked to develop a simple CRUD events man...

17_February_2020

Continuous Deployment(CD) Using Bitbucket Pipelines and Ubuntu Server

Introduction: In this tutorial, you will learn how to set up Bitbucket Pipelines for a PHP & No...

22_January_2020

How To Stay Productive When Dealing With Anxiety Disorder

Disclaimer: This isn't really a hack. There are no eight steps to beat any kind of disorder. If you'...

8_January_2020

Setting Expectations for Software Engineering Teams

Introduction When I started at Andela as CTO I had an opportunity to introduce myself and set expec...

19_December_2019

Battle-tested hacks to grow exponentially as a software engineer

So, you just switched careers and now you are into tech, a software engineer or you have been doing ...

9_December_2019

Partners

Tap into a global talent pool and hire the “right” developers in days, not months.

Developers

Accelerate your career by working with high-performing engineering teams around the world.

BECOME A DEVELOPER

Hire Developers

We take great pride in matching our developers with the best partners. Tell us about your team below!

preloader_image

Thank you for your interest

A member of our team will reach out to you soon.