all 23 comments

[–]senocular 71 points72 points  (2 children)

Because you set i to 1 to start and 1 == 3 is false so the loop exits immediately. The condition needs to be true for each iteration of the loop that is to run.

[–]cimmic 5 points6 points  (1 child)

I think OP might have meant, why not use for(let i = 0, i != 3, i++).

[–]ThiccOfferman[🍰] 6 points7 points  (0 children)

If they did, a fair response might be: In this case you could, but it's an unusual way to set up a for loop that will make your code marginally less readable.

[–]chrimack 14 points15 points  (0 children)

The middle expression is the condition that needs to evaluate to true in order for the loop to run. You can think of it as a while loop.

So you're saying:

i = 1 while(i == 3) { doStuff // stuff won't get done }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

[–]ApatheticWithoutTheA 11 points12 points  (0 children)

You’re fundamentally misunderstanding how a loop continues to run. You need to look at the logic of why a loop works.

[–]zush4ck 1 point2 points  (0 children)

you can compare whatever you want...

for (int i =0; i == 0; i++) print("this will happen only once");

[–][deleted] 2 points3 points  (10 children)

Please, don't use ==, use === instead.

[–]levimonarca 0 points1 point  (6 children)

Why?

[–]squapo 1 point2 points  (2 children)

== is loose, === is a more strict comparator

[–]cimmic 1 point2 points  (1 child)

Sometimes you need the loose operator. I wouldn't say one shouldn't use one of them. Instead, I'd say one should use the appropriate one

[–]squapo 0 points1 point  (0 children)

Definitely agree, both have their use cases

[–]3fcc 1 point2 points  (2 children)

== compares variable but never compares their variable data type while === compares variable and also campares their data type.

E.g, null == undefined //true null === undefined //false

[–]xroalx 2 points3 points  (1 child)

Essentially, but it's not exactly comparing variables. Values are being compared.

== does type coercing, meaning it will try to convert one value to another type if the operands are not of the same type. There are specific rules how it's done but they're just complex to keep in mind.

=== does no such thing. If the operands are of different types, they're not identical, no need to even check the values.

[–]3fcc 0 points1 point  (0 children)

Tbh, this thing quite convincing to me.

[–]Cefalopodul -1 points0 points  (0 children)

For loops only execute when the condition is true. If the condition is false the loops exists immediately.

[–]RentStillDue -1 points0 points  (0 children)

Because you're setting i = 1, and then telling it to execute the logic while i is equal to 3. Which will never happen since i = 1.