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.
CodePudding user response:
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
CodePudding user response:
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.
CodePudding user response:
The second part of for loop is condition; and boolean result of that condition tells the for loop to stop or continue; when you put 10
it will be evaluated as true; hence for loop never end; as if you writing
if (10) {
// do something
}
CodePudding user response:
If you are not wrapping the logic inside brackets, then it will divide like this
either it will check a<num
is true or 10
is a true expression.
It taking 10 as a true expression because its a non zero number. So every time the loop getting the second expression as true and so on.
If you wrap the condition then it will check like this
either a<num
or a<10
It will stop when it match any of the expression false.
It just the use of brackets.
CodePudding user response:
The reason is because of the Operator Precedence in JavaScript (or any language).
When you pass the expression a<num||10
to your for loop's break condition, it evaluates the a<num
part first, and then the ||10
part.
a<num
will provide you with a true/false value and 10
will give you 10 (a truthy value), hence a<num||10
will essentially check if one of a<num
or 10
is a truthy value, which is true. Therefore, the infinite loop.
More on Operator Precedence:
MDN Docs
CodePudding user response:
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 )