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)