This is my code snippet
const loopFn = function(num) {
for(let a = 0; a < num || 10; a++) {
console.log(a)
}
}
let b = loopFn(8)
console.log(b)
I know the correct way to write is a < (num || 10), I'm just curious why it causes an infinite loop instead of reporting an error.
What you mean do to is
const count = num || 10;
for(let a = 0; a < count; a++) {
console.log(a)
}
But what you're actually doing is saying while a is less than 8 OR 10 is true
The language/execution engine does not report it as an error because there is no inherent issue with infinite loops itself.
Depending upon the use-case infinite loops are of help. For instance, in daemon scripts that are meant to process jobs from a queue.
The condition of your for loop is:
a < num || 10
If either a < num is true, or 10 is true the loop continues.
Try in your browser console, and you will see, that 10 is always true. if(10) alert("true")
If you want the loop to end if a is not < 10, try this:
for(let a = 0; a < num || a < 10; a++)