FAQ: Loops - The For Loop


#1

This community-built FAQ covers the “The For Loop” exercise from the lesson “Loops”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise The For Loop

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

I created a “for” loop as below:

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

The expected result was a short list of numbers: 5, 6, 7, 8, 9, 10
Yet, the returned result was a lot of “5” digits.

To me, the iteration statement “num+1” is synonymous with “num++” and “num+=1”; the latter two worked fine.
I don’t know why I got different results using the three statements.

Can anyone do me a favor and answer this question? :confounded:


#3

they are not the same, num + 1 never updates the num variable. We can see this:

let i = 5;
console.log(i + 1) // 6
console.log(i) // 5, because variable didn't update. 
i = i + 1
console.log(i) // 6

i = i + 1 does update the variable, += is just a shorthand, and ++ is even shorter shorthand to increase the variable by one

i = i + 1 looks a bit weird for new programmers, because you assign the current value + 1 in the same variable.


#4

Why doesn’t this work?

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

#5

you can’t use the or operator in the for loop. Besides, why would you? counter starts out as 5, and only increases, so counter > 4 is redundant.