'The following javascript code gives output 6 . How the code is executed? [closed]
Why the output of the following code is not (1,2,3,4,5)?
var x = 0;
while (x < 6) {
x++;
}
document.write(x);
Solution 1:[1]
That is because you are only writing to the document once.
For this, you should probably use a for loop.
for (let x = 0+1; x < 5+1; x++) {
document.write(x);
}
This says x = 0 + 1 = 1 (so it starts at 0), then for every x > 5 + 1 (the +1 is so it ends at 5) do this, then add 1 to x.
Simply: x = 1, then when x is over 5, it will write to the document, then it will add 1 to x to continue the loop.
Solution 2:[2]
Each time the loop is repeated, the value in the x variable is updated. x++ increases the value of x by one unit And you write the final value
Solution 3:[3]
This example shows how to achieve this:
var x = 0;
let myArray = [];
while(x<6) {
++x; // We want x to start at 1
myArray.push(x) // Add the new value of x into the array
}
const string = '(' + myArray.join(',') + ')'; // Format the output string by joining the array in a csv format and wrapping with brackets.
document.write(string);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ethry |
| Solution 2 | FatemeZamanian |
| Solution 3 | Simon K |
