DEV Community

aKuad
aKuad

Posted on

Alternative of 'for' in JavaScript

Introduction

There are some cases of processing elements in Array. Basically solution is process with for.

Actually, there are other solutions without using for. Them can reduce code and keep code in simple.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array

Tutorial - Arrow function expressions

These codes will be take same behavior.

function (e) {
  return e*2;
}
Enter fullscreen mode Exit fullscreen mode
e => { return e*2; }
Enter fullscreen mode Exit fullscreen mode
// if one liner with return, write without return
e => e*2
Enter fullscreen mode Exit fullscreen mode

By using =>, you can omit function, {} and return.

Do some processes to each elements in an Array

E.g. multiplex x2

const input  = [1, 2, 3, 4];
const output = [];

for(let i = 0; i < input.length; i++) {
  output.push(input[i] * 2);
}
// output: [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode
const input  = [1, 2, 3, 4];
const output = input.map(e => e*2);
// output: [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

Other example: Extract elements from objects in Array

const files = document.getElementById(any-input-element).files
const files_name = Array.from(files).map(e => e.name)
//                 ~~~~~~~~~~~~~~~~~
// Convert to Array from FileList
Enter fullscreen mode Exit fullscreen mode

Actually, Array.from() also has same feature of .map().

const files_name = Array.from(files, e => e.name);
Enter fullscreen mode Exit fullscreen mode

It can be able to use .map() to array-like object.

Extract elements what match to a condition

E.g. Extract even numbers from Array

const array     = [1, 2, 3, 4];
const array_use = [];

for(let i = 0; i < array.length; i++) {
  if((array[i] % 2) == 0) {
    array_use.push(array[i]);
  }
}
Enter fullscreen mode Exit fullscreen mode
const array     = [1, 2, 3, 4];
const array_use = array.filter(e => (e % 2) == 0);
Enter fullscreen mode Exit fullscreen mode

Check is a value in Array

E.g. Check is input string ‘caution’, ‘warn’ or ‘danger’

const input = "warn";
const true_cases = ["warn", "danger"];

for(let i = 0; i < true_cases.length; i++) {
  if(input === true_cases[i]) {
    // Process for correct
  }
}
Enter fullscreen mode Exit fullscreen mode
const input = "warn";

// For only few true cases (about 1 or 2), this solution may be the best
if(input === caution || input === "warn" || input === "danger") {
  // Process for valid case
} else {
  // Process for invalid case
}
Enter fullscreen mode Exit fullscreen mode
const input = "warn";
const true_cases = ["warn", "danger"];

if(true_cases.includes(input)) {
  // Process for valid case
} else {
  // Process for invalid case
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Sometimes let’s see documentation (language reference, command help and so on).

You may find good functions, methods or options.

Top comments (0)