Handling undefined in a for ... of loop?

Viewed 1165

Suppose my code is as follows:

const days = ['Monday', 'Tuesday'];

for (const day of days) {
  console.log(day);
}

It prints out 'Monday' and 'Tuesday'.

If for whatever reason, days is undefined, then I get a runtime error.

I could handle this by putting in code like the following:

if (undefined == days) {
  // logic here
}

To me, that seems a little clunky. Is there a way to have the for ... of loop ignore undefined values? Basically, treat it like a zero-length array and so the logic inside the for loop won't execute, but it won't throw an error either.

2 Answers

You could always use a forEach, and a logical or || within a parenthesis block.

(days||[]).forEach(day=>{console.log(day)});

I suppose you could also use this in your for loop.

for(let day of (days||[])) {
   console.log(day);
}

The best way to check for a empth value is to initialize a variable before using it, Either is a string, object or array. This way the programm understand the variable and can easily suggest function for you.

  //Initializing Varable
  let stringVariable = '' ;
  let objectVariable = {};
  let arrayVariable = [] ;

In your case

 let days = []
 for(let day of (days)) {
  console.log(day);
 }
Related