FAQ: Loops - The For Loop

Aren’t all three iteration run at the same time ?? (First iteration =declaration ;second iteration (true or false) ; third iteration ( do this until 2nd iteration false) ) ??
Sorry if question seems stupid.

The increment only takes place after the code body has run. The iteration variable is checked by the middle condition, and if still within range, the increment takes place, else the loop terminates.

1 Like

Hi, could you explain why this code won´t work?

for (let counter = 0; counter >= 5 && counter <= 10; counter++){

    console.log(counter);

}

thanks!

the loop condition is false? 0 isn’t greater then or equal to 5, so the loop evaluates to false right away

2 Likes
for (let c = 5; c < 11; c++) {
  console.log(c);
}

is the same as

for (let c = 5; c < 11; c++) 
  console.log(c);

However, Codecademy was not happy when I ran it, even though I got the right output.

The end braces denote a block, which is a good habit to form. Your second example is inline and can raise some problems, mainly leakage of the variable into outer scope. The block braces confine the variable to that scope.

Your second example is inline and can raise some problems, mainly leakage of the variable into outer scope.

I do not see how it may lead to a variable leaking. With the braces omitted, the first line is considered to be in the loop body. Of course, writing more lines without the braces is erroneous.

Actually, you are right. c is not leaking, as first suspected.

Which would include writing multiple statements (semi-colon separated). The second statement would be outside of the loop.

Bottom line, good practices help us to develop good habits, and generally fit in better with other collaborators.

Can someone explain why this doesn’t work as a solution, when the output is correct?

for (var num=5; num<11; num++){ console.log(num); };

Do I must use “let” and not “var”?

Have you tried it? The SCT may be expecting let.

Yes Let works. I just wondered if there is a different use for let and var or are they interchangeable.?

They are marginally interchangeable, though let is more scope focused. var gives us function scope, where let gives us block scope which includes loops and other block constructs (if, while, switch, etc.).

2 Likes

I was experimenting a little bit with the first ‘for’ loop exercise. I wanted to see if I could somehow fit in a function into the loop and see if it’d run.


It didn’t run ofc, but it didn’t show any errors either. So I decided to bring my work to the forum and ask if there is a way how this can be done.

This looks an infinity loop. I don’t think this will work, the increment will not persist.

Hi everone,
**Could some shed some light on why the following code

const nums = [1, 2, 3];
for (let i = nums.length - 1; i >= 0; i–) {
console.log(nums[i]);
}
console.log(‘Time is up!’);

would prints this?
3
2
1
Time is up!

When my expectation is the following (due to num.length minus 1 which is 2, so it should count down from 2, but it is starting the count from 3 and ignoring the minus 1)
2
1
Time is up!

There’s the why… nums[2] is 3

I’m revisiting this topic, and I realized that I use var an awful (or maybe not-so-awful :rofl:) lot in my code… @stetim94 I’m wondering if what you mean by “and not even var” is that using var instead of let is a bad practice?

Not to butt in, but time’s a-wasting. There is no connection to bad practice. var is still valid since JS is backward compatible. Only thing it lacks is block scope. It retains function scope, though, which was the intention all along, pre-ES2015.

Variables that are defined without declaration are automatically var in global scope with bindings to the ‘window’ object, if I’m not mistaken.

function foo() {
   a = 42
}
console.log(a)

In a function, using var or let is moot at top scope. They are both accessible from any inner scope.

The paradigm has shifted somewhat, but that only points to a slight change in thinking. Once we think in terms of leakage and go backwards, it all falls into place in our common practice. Even in ES5 days we still had the ‘no polluting global scope’ proviso. All block scope has brought to the table is refinement of where variables get garbage collected. Once any block is exited it gives up the memory its let or const variables used since their references no longer exist.

All along, var declared variables lost their references when a function was exited. This keyword has the same purpose and value it always had. If it slips in now and then, it’s not a sin if it is in function scope. If we use it in a block, then it is still okay, but we know the variable will leak out of the block. This could be good thing, when we think about it. Remember, inside a function we have a general rule of always declaring local variables. So any new variable should be declared. Maybe we have a use for that variable at the end of loop or switch, for instance. More proof of validity and usefulness.

2 Likes

The other day a topic surfaced asking what was the difference, to which I postulated it is one of binding. Let’s see if this plays out.

 > var a = 42
=> undefined
 > a
=> 42
 > window.a
=> 42
 > let b = 6
=> undefined
 > let c = 7
=> undefined
 > window.b
=> undefined
 > window.c
=> undefined   

That tells us that let in global scope has no binding to window. Something that may be worth knowing somewhere down the road.

Let’s see how that applies to undeclared local variables of a function.

function foo() {
    z = 42
}
foo()
console.log(window.z)    //  42

This supports our earlier assumption that undeclared variables are var declared in global scope since they have window binding. Also something to know for the future, for whatever purpose it serves.

3 Likes

2 posts were split to a new topic: Why does ‘for’ use ‘;’ between parameters?