Trying to understand this Code I came across Picture provided

Hey guys…This weekend I did a freelance project where I had to create a word wrap function and I ended up just copying some code from overstack flow because I was running out of time to get the job done but now that i’ve finish I’m really struggling to understand what’s take a place and would like a nudge in the right direction of understanding… Maybe i’m misunderstanding some core concepts or something but the code is in the image below. Most of the struggle is with the IF statement and how the string is actually being broken up.

See if you can explain to us what you think the code is doing. We can correct you if you are wrong.

FYI - You are creating many global variables that might eventually cause you problems in other parts of your application and/or this particular function.

Let me try because like I said I grabbed the code for a guy who wanted just something basic code to run it.

But I believe of course newLineStr creates a newline of test. The while statement continues running while the str.length is longer than the maxWidth (I have no idea when the length shrinks)

the for loops run through and checks if there’s white space and then I get confuse on how the function actually starts going to the next line and next line . I just look at the slice and see it just being stuck on one line . I don’t really see how it moves to the next line to process. I think I start getting lost at trying to see how the functions goes through and moves to new slices to look at in the original string

The for loop is in charge of each line, the while loop runs each for loop while there is still more wrapping to do.

The for loop wraps the line at the first whitespace character present while iterating over the string in reverse order. If no whitespace character is found, the string is wrapped at the maxWidth.

Whitespace character can be any of the following: \r \n \t \f \v