2

I need to figure out how to output a list of numbers in a loop to the console. However, the output to the console must be in the same line, as opposed cascading down the page with every new number. Below, I have two separate blocks of code that accomplish the same thing. One uses a while loop and the other uses a for loop. If there's a difference between being able to accomplish this in a for loop versus a while loop, I'd like to know that as well. Thank you.

While Loop

var number = 2;

while (number <=10) {
console.log(number++);
number = number + 1;
}

For Loop

for (var number = 2; number <= 10; number = number + 2)
console.log(number);
1
  • 4
    you want the console output to be one line, or the code to be one line? Commented Oct 10, 2015 at 4:37

2 Answers 2

4

To keep it simple, all you need to do is concatenate the numbers to a string that you keep track of. Every time you console.log, it will automatically move it to a new line.

var output = ""; 
for (var i = 2; i <= 10; i = i + 2) {
    output += i + " "; 
}
console.log(output);

The type of loop you use doesn't matter.

Sign up to request clarification or add additional context in comments.

Comments

2

While:

var number = 2, output = [];
while (number <=10) {
    output.push(number++);
    number = number + 1;
}
console.log.apply(console, output);

For:

var number, output=[];
for (number = 2; number <= 10; number = number + 2) {
    output.push(number);
}
console.log.apply(console, output);

Note, I would recommend you don't do for(var x... - it gives a false sense of scope for the var x - but that's just opinion on my part

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.