Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[JavaScript] Check if iterator is undefined when using a for…of loop

Just saw this trick, how you can do a for…of loop which also checks if the iterator is null or undefined. Normally, you would check this by another if statement before starting the for..of loop, like here

const d = undefined

if (d) { 
  for (const x of d ) {
  	console.log(x)
  }
} 

or by using a try...catch

try {
  for (const x of d) {
    console.log(value)
  }
} catch (e) {
  console.error(e) // TypeError: undefined is not iterable
}

But instead of if or try...catch, you could use d || [], to check if d is Falsy, and if it’s false, no iterations are performed and no errors are thrown. The disadvantage of this approach is that you create an unneeded array and the readability may be poor depending on the situation.

for (const x of d || []) {
	console.log(x)
}

Of course, the first and the last snippet can also be done in one line

if (d) for (const x of d ) console.log(x) 

for (const x of d || []) console.log(x)

[JavaScript] Iterate

While Loops

var myArr = [];
var i = 0;

while(i < 5) {
  myArr.push(i);
  i++;
}

For Loops

var myArr = [];

// for ([initialization]; [condition]; [final-expression])
for (var i = 0; i < 5; i++) {
  myArr.push(i);
}

Iterate through an Array with a For Loop

var myArr = [ 2, 3, 4, 5, 6];
var total = 0;

for (var i = 0; i < myArr.length; i++) {
    total += myArr[i];
}

Nesting For Loops

var myArr = [
  [1,2], [3,4], [5,6]
];

for (var i=0; i < myArr.length; i++) {
  for (var j=0; j < myArr[i].length; j++) {
    console.log(myArr[i][j]);
  }
}

For…In Loops

Iterate through all the keys within an object.

let users = {
  Max: {
    age: 27
  },
  Mira: {
    age: 32
  },
  Rich: {
    age: 48
  }
};

for (let user in users) {
  console.log(user); // logs: Max, Mira, Rich
  if (users[user].age > 40) {
      console.log(`${user} is old.`);
  }
} 

Do…While Loops

A do...while loop ensures that the code inside the loop will run at least once.

var myArr = [];
var i = 0;
do {
  myArr.push(i);
  i++;
} while (i < 5);

Replace Loops using Recursion

/* For Loop */
function multiply(arr, n) {
   var product = 1;
   for (var i = 0; i < n; i++) {
       product *= arr[i];
   }
   return product;
}

/* Replace For Loop with Recursion */
function multiply(arr, n) {
   if (n <= 0) {
     return 1;
   } else {
     return multiply(arr, n - 1) * arr[n - 1];
   }
}

Note: Recursive functions must have a base case when they return without calling the function again (in this example, when n <= 0), otherwise they can never finish executing.

/* Count to n */
function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}

console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]

Note: The push happens last, after the recursive call has returned. Thats why the value of n decreases, but the values in the final array are increasing.

/* Create a Range of Numbers */
function rangeOfNumbers(startNum, endNum) {
  if (startNum == endNum) {
    return [startNum];
  } else if (startNum < endNum) {
    const rangeArray = rangeOfNumbers(startNum + 1, endNum);
    rangeArray.unshift(startNum);
    return rangeArray;
  } 
};

console.log(rangeOfNumbers(5, 10)); // [ 5, 6, 7, 8, 9, 10 ]