0

I currently have this small script that outputs a value after each iteration of a while loop:

var i = 0;
var number = "";

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

Which creates this output:

0
1
2
3
4
5
6
7
8
9

However, I am testing some API calls and using the while loop in JavaScript to see if I can send values consistently, so my values are coming from the script below:

var i = 0;
var number = "";

while (i < 10) {
    number += (i);
    i++;
}

I do not need console.log() because I do not need the output in the terminal. My issue is when looking at the output on the receiving end when using the API, it looks something like this:

0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789

The API calls are in the while loop as well, I did not include them because I feel this is a JavaScript syntax related issue. So what will happen is that the while loop begins, number is iterated, that value is sent to a website using an API call, and the the while loop begins again. Something like the code below:

var i = 0;
var number = "";

while (i < 10) {
    number += (i);

    API_Send(number)

    i++;
}

What can I do to so that the output of each iteration is its own separate variable similar to the output using console.log(), so first iteration is 0, second iteration is 1, and so on.

I feel this is something that would be necessary when outputting values to be used by a function. So perhaps it is best to create a function that has a while loop outputting integer values?

2
  • 1
    var number = ""; You're concatenating. Initialize number to 0 instead, or reassign number completely Commented Nov 1, 2018 at 7:14
  • Why you don't use for (i = 0; i < 10; i++) { do something... } it will simple. Commented Nov 1, 2018 at 7:18

1 Answer 1

3

The problem is that you have declared number as string, don't do that just assign 0 to number variable. Because of string variable javascript is concatenating the numbers.

Change as following:

var i = 0;
var number = 0;

while (i < 10) {
    number += (i);

    console.log(number)

    i++;
}

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

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.