0

can anyone tell me why this loop produces an almost infinite negative numbers despite I specified that it shouldn't exceed -10?

for (var person = 2; -10 < person < 10; person --) {
    console.log(person);
}

I expected it will count from 2 to -10

  • In short: you can't chain `<` in JS, the condition should be written in 2 parts with an "and": `-10 < person && person < 10`. (`&&` is the "logical and", because there is a "bitwise and" too, `&`). – tevemadar Dec 30 '22 at 12:00
  • that's very elaborative, thanks ^_^ – adham elkady Dec 30 '22 at 12:02

2 Answers2

1

Change your current code to this-

for (var person = 2; person >= -10; person --) {
  console.log(person);
}
Neha Soni
  • 3,935
  • 2
  • 10
  • 32
Raziak
  • 360
  • 1
  • 7
0

if you want to check if a number is between two other, you should go like this

for (var person = 2; -10 < person && person < 10; person --) {
    console.log(person);
}

when you chain -10<person<10, it gets interpreted as ((-10<person)<10), and first one is true till it becomes lesser than -10 or equals to it, so first the first part till it person becomes -10 it is like (true<10) and true is 1.so it returns true. for the second part when person becomes lesser or equals to -10 (-10<person) returns false and false is 0 and it surely is lesser than 10 --> (false<10), so it stays true forever and there goes infinite loop.