FAQ: Loops - The For Loop

Hi guys,

When I run console.log(userChoice(‘A’)) on the last line of code it runs the correct loop but then ends with the word undefined. How do I remove the word undefined and just log the results from the loop to the console?

Thanks everyone!

countToThree = () => { for (let i = 1; i <= 3; i++) { console.log(i) } }; runAway = () => { return 'Game Over.' }; userChoice = (choice) => { if (choice === 'A') { return countToThree() } else if (choice === 'B') { return runAway() } else { return 'Input not valid. Select A or B.' } }; console.log(userChoice('A'))

your countToThree function doesn’t return anything. So when we choice A, we get undefined

Either: make your countToThree return something, or you need to do a check that the returned result is not undefined:

const result = userChoice('A')
if (result)
{
   console.log(result);
}

Why does the example shown:
for (let counter = 0; counter < 4; counter++) {
console.log(counter);
}

print: 0, 1, 2, 3
since counter is being updated before it can print shouldn’t it start by printing 1?

1 Like

counter is not being updated before it can print. The final parameter only comes into effect at the end of the loop body, followed by the conditional test. These are parameters, not inline code.

But that is a great question. Why the “stopping condition” works in the first iteration, but the counter does not?

for (let counter = 4; counter < 4; counter++) {
console.log(counter);
}

That should print 4… but it does not.

The loop is never entered since the ‘run state condition’ failed.

  • initialize
  • test against condition
  • if condition passes, enter loop body and execute code
  • increment counter

Exactly, that makes sense. But if the condition does not passes, then the variable still ha the same value, right?

If those are parameters, not line code, when I print the variable, it should print the last value. But it does not.

Yes, the variable still refers to the number, 4. The line in the loop does not execute so there is no logging. Try logging after the loop.

Sorry, but I get an error saying that “counter” is not defined. That’s because the variable counter is only in the scope of that funcion, right?

I believe we will have to just accept that… there is no really any rational behind it, I would say. It is what it is.

So what happens here:

for (let counter = 0; counter < 4; counter++) {
console.log(counter);
}

1.Set the variable to 0
2.Check the condition
3.If true, prints the variable
4. add one to the variable value

I tried this:

for (let counter = 3; counter >= 0; counter–){

console.log(‘blah’);

}
And it printed

blah
blah
blah
blah

So that is it. If the condition is true, it runs the function first.

Thank you @mtf for your patience and for answering so quickly. Really appreciate it.

1 Like

You discovered block scope, and the reason we cannot print counter after the loop. Remove let from the initialization to expose it to outer scope.

That is, the code block. The code is not a function. for is statement, as are the lines enclosed in its body.

1 Like
for (let trax = 5; trax === 11; trax++){
  console.log(trax);
}

for (let trax = 5; trax = 11; trax++){
  console.log(trax);
}

Why doesn’t these two work ?

The first loop evaluates false at its first iteration, given 5 does not equal 11.

the second loop, the assignment will simple result evaluate a positive integer as truthy

1 Like

A numerical for loop generally iterates over a sequence made from the values in an interval… The iteration variable takes on a new value from the sequence as long as the value falls within the interval.

The middle parameter is meant to be a conditional expression, not a statement (trax = 11 is a statement) which will result in an infinite loop. That would be bad for any program as the only way to stop it is to intervene with the task manager and kill the process. Definitely do not want that.

As to the interval, we can test if our current value falls within it by using an inequality expression.

x = 5; x <= 11; x++
       _______

The inequality reads, x less than or equal to 11 which qualifies all the integer values, `5, 6, 7, 8, 9, 10, and 11, after which the loop terminates.

~~Apologies if this has been asked already, I scrolled through and didn’t see it, albeit I was skimming the more complicated parts as I just started this exercise. I’m wondering if you always have to create a variable in the for loops parameters first? If not, what else could you put in there, for instance if I created a variable outside the for loop first and wanted to use that, would it just be (as per the example in the exercise)

let counter = #;

for (counter = 0; counter < 4; counter++) {  c
onsole.log(counter);
}

Instead of let counter?

Edit: Found out that yes, this can be done, in which case you just leave the first statement blank and leave a ; as so:

let counter = 0;
for (; counter <= 10; counter++){}

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

Is also valid, if anyone wants to write a simple 1 line for loop that has only 1 action statement.
The exercise is looking for the conventional block form syntax. But I believe the above syntax
is considered acceptable if it has only 1 statement. In this case, the console.log

But I think if you’re working for a company and they frown upon this practice, regardless of how simple the for loop is, you better follow their lead.

So my initial attempt was:

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

It responded that it was incorrect despite giving the correct answer.

My Correct Answer, (avoiding spoilers if you're only looking for insiration).

I realised it simply wanted me to add a “let” in:

for (let counter = 5 ; counter < 11; counter ++){
  console.log(counter);
};

My question is:
Is this just a case of it doesn’t matter if you include it but this is just how it’s marked in this || could i encounter problems in the future from omiting it?

Welcome to the forums!

When you declare a variable without var, let, or const, you implicitly create a global variable. Doing this can cause many unexpected errors.

You should almost always declare variables, whether they’re used in for loops or not, with either var, let, or const, depending on your use case.

3 Likes

Thank you so much and that answers my question wonderfully!

Just me explaining my understanding on this and a further question but I'm not sure if this counts as a deviated topic so I’m wrapping it in spoilers just in case it breaks the relevancy rule? Sorry if it does!

Sorry if this was already covered and I just forgot but until this I was presuming that when i declared a variable within a type of function it would by default create a variable with function/local scope.

I’ve tried doing some extra reading from your reply and I think it’s because of “JavaScript Hoisting” but I’m still not completely sure why Hoisting even exists.

I now know that:

Hoisting is JavaScript’s default behaviour of moving all declarations to the top of the current scope (to the top of the current script or the current function).

And when we assign a value to a variable that has not been declared it’ll automatically create a global declaration for it and thus risk scope pollution so I don’t know why we would want it to do that by default but I think I now understand why we should almost always declare a variable with either let, const or var.

My questions:
Is it worth it for me to try and properly/fully understand how/why hoisting exists in JavaScript right now or should I just press on with the course and hopefully learn it more easily once i have a more holistic understanding of all this in general?

Sorry it’s a long message and Thank you again for your time! - Augustus

I always advocate for taking the time to properly understand different programming concepts, though if you feel that you’d be able to better understand it once you finish the course, you can always revisit it then. Either way, I’d strongly recommend gaining a good understanding of hoisting sooner rather than later.

This article is a great read on the subject and provides a pretty good overview of hoisting in JavaScript: What is Hoisting in JavaScript? (freecodecamp.org)

4 Likes