0
let cows = 4;
let width = 4;

let string = cows.toString();

while(string.length < width) {
  string = "0" + string;
}

console.log(string);

This code will be printed as 0004..what i dont understand is why it doesnt print out 04040404?

2
  • 1
    Why not put a console log inside the while loop and see? Commented Mar 31, 2021 at 9:16
  • Why do you expect that output? The code is only ever prepending a zero to the current string? Commented Mar 31, 2021 at 9:25

1 Answer 1

2

So, at the start, your string is "4".

Then you enter the while loop, and your string becomes "04".

The condition isn't met yet, so you loop and add another '0' to the beginning of your string, becoming "004".

You loop one more time, adding again '0' to the start of the string, making it "0004".

Here your condition is met, and you exit the loop.

To obtain the result you had in mind, something like this would've worked

let cows = 4;
let width = 8;

let string = cows.toString();
string = "0" + string;

while(string.length < width) {
  string +=string;
}

console.log(string);
Sign up to request clarification or add additional context in comments.

5 Comments

In case of a width that's a factor of two, yes, otherwise this won't give the desired result.
thank you for the response but why does the while loop adds the 0 in the beginning of the string and not the end?
@Valch Because the order matters. if you write string + 0 , you'll have "40", but if you write 0 + string, you get "04"
alright, sorry if im being stupid, why is the while loop ignoring the string value but adds only the 0 even tho its "0" + string?
@valch No worries, we all started somewhere. The string value is not being ignored, otherwise you would just write over whatever is inside the variable string, and you would end up with "0" at the console.log. Picture a box, in which you place a paper with "4" written on it. Then you take out the paper, staple another paper with "0", and place the result back in the box. And again, and again. That's what is happening

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.