You can do it without loop

Introduction

In this article you you learn to living without loops. By loops, I mean for loop, while loop and do while loop. There are various ways of doing things, in javascript there are you can most of the things without loops.

Doing things without loops could do these things

  • makes code simple and readable
  • gives you better performance
  • Increase the standard of code

Common operation of loops

What are the common operation which we do with the help of loops ?

There are lots of operation which are done using loops and most of them can be done without loops.

  • Filtering of data
  • map data to some other value
  • iterating over the data

Here data means array of data.

map()

map help us in transforming data to something else.

It is called map because it map one value to some other value.

// We are having users details with salary in `Euro`
let salaryInEuro = [
    { id : 1224 , name : 'kat', salary : 4320 },
    { id : 1247 , name : 'sam', salary : 6320 },
    { id : 1294 , name : 'july', salary : 8320 }
];

// We have to convert users salary to the `Dollar` from `Euro`

// First of all we write a function which can convert dollar into salary of on user
// One user data can be represent like this 
// { id : 1224 , name : 'kat', salary : 43200 };

/**
 * @value value of array item
 */
function transform(value){
    value.salary = value.salary * 1.1;
    return value;
}

let salaryInDollar = salary.map(transform);

filter()

Filter help us in filter the array data based on condition.

It is called filter because it filter the data based on the condition.

// We are having users details with salary in `Euro`
let employees = [
    { id : 1224 , name : 'kat', salary : 4320 },
    { id : 1247 , name : 'sam', salary : 6320 },
    { id : 1294 , name : 'july', salary : 8320 }
];

// We want all the get the user whose salary is greater then 5000.

// First of all we write a function which test if the user 
// salary is greater than 5000 or not.

// One user data can be represent like this 
// { id : 1224 , name : 'kat', salary : 43200 };

/**
 * @value value of array item
 */
function condition(value){
    return value.salary > 5000 ;
}

let topSalaryEmployees = salary.filter(condition);