You Don’t Need Loops in JavaScript




You Don’t Need Loops in JavaScript

You Don’t Need Loops in JavaScript

1. To Loop Through All Elements and Get an new modified array

Using loop:

var names = ["Jack", "Jecci", "Ram", "Tom"];
var upperCaseNames = [];
for(let i=0, totalNames = names.length; i< totalNames ; i= i +1) {
    upperCaseNames[i] = names[i].toUpperCase();
}

Without loop:

var names = ["Jack", "Jecci", "Ram", "Tom"];
var upperCaseNames = names.map(name => name.toUpperCase());

2. Loop through all elements and perform an action

Using loops

function print(name) {
   console.log(name);
}
var names = ["Jack", "Jecci", "Ram", "Tom"];
for(let i=0, totalNames = names.length; i< totalNames ; i= i +1) {
    print(names[i])
}

without loop

var names = ["Jack", "Jecci", "Ram", "Tom"];
names.forEach(name=> print(name));

Using filter:

var numbers = [1,2,3,4,5, 6, 7]
var odd = numbers.filter(n => n%2); // single line

Using reduce:

var numbers = [1,2,3,4,5,6,7];
function sum(accumulator, currentValue){
   return accumulator + currentValue;
}
var initialVal = 0;
var result = numbers.reduce(sum, initialVal);

The above code can be even more simplified:

var numbers = [1,2,3,4,5,6,7, 10];
var result = numbers.reduce((acc, val)=> acc+val, 0);

 


Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.



News & Blogs

b155c4808d155c5ed54a2d70f917f6ea.png

An Introduction to Angular: The Remarkable JS F...

Javascript frameworks have nowadays become the most popular and most-used web app development sol...

0752431b16084e2bc68868f7908c94a1.png

Develop RESTful API using Node JS, Express JS

REST (Representational State Transfer) is web standards based architecture and uses HTTP Pro...

6f5026c52c20b8aa8e6452b8934aa46b.png

How to Build a Real-time Chat App With NodeJS, ...

In this tutorial, we’ll be building a real-time chat application with NodeJS, Express, Sock...