1

Say I have a for-loop

for (let i = 6; i <= 10; i++) {
    console.log(i);
};
/* 
logs the expected... 
6 
7
8
9
10
returns undefined
*/

But if I cast those numbers as strings...

for (let i = "6"; i <= "10"; i++) {
    console.log(i);
};
// logs nothing, returns undefined

What exactly is happening here to seemingly short-circuit this loop?

Dru Serkes
  • 76
  • 7

4 Answers4

1

The real explanation is that your for loop is evaluating the lexical values of "6" and "10". The lexical order of strings goes like this: 1, 10, 2, 3, 4, 5, 6, 7, 8, 9

Like any other string, it sorts by the string characters, in order, so you can think of it ordering in the same way it orders strings with letters.

Therefore, the loop condition immediately evaluates to false, so it never executes the block where you log the value.

Steve Storck
  • 793
  • 6
  • 25
0

In the second case you are comparing string values that's why the condition of the loop is false.

'6' <= '10' is false

Sifat Haque
  • 5,357
  • 1
  • 16
  • 23
0

It's all about the values of string that it holds, "10" is less than "6" that's why it is returning undefined.

0

<= is computing whether the left-hand-side is lesser or equal than the right-hand-side.

6 <= 10

is true, because 6 is a number that's lesser than 10.

'aaaaaaaaaaaa' <= 'z'

is true, because as a string, aaaaaaaaaaaa is lesser than z.

'6' < '10'

is false, because 6 is alphabetically greater than 10. So, when they are strings, they are compared alphabetically, this is the reason of the different outputs you have encountered.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175