Can someone explain me this code?

Can someone explain me this code?
0.0 0

#1

Its been a long time since i was doing for loops. I forgot a few things. Now im doing JavaScript from w3schools and im curious about this code here at JS String methods where for loop is used.
https://www.w3schools.com/js/tryit.asp?filename=tryjs_string_split_char

Why did he create var text?
And can someone explain me" text += arr[i] + "<br>""part?


#2
str = "Hello"
 arr = ["H", "e", "l", "l", "o"]
text ="H<br>e<br>l<br>l<br>o<br>"

The loop is used to add <br> after each character.

text += arr[i] + "<br>""
The variable text is a string and is incremented ( += ) each round by the value arr[i]<br>.
It means:
1 round:
text = H<br>
2 round:
text = H<br>e<br>
3 round
text = H<br>e<br>l<br>
4 round
text = H<br>e<br>l<br>l<br>
5 round
text = H<br>e<br>l<br>l<br>o<br>


#3

Ok but why would he create empty string (var text)? Why wouldnt he use just already existing text of str (var str= “Hello”)?


#4

The whole point of the exercise is to teach you how you could rebuild a new string from an array. The variable text must start as a blank string “” for the concatenation to work as desired.


#5

Ok thank you, i’ll do more for loops in the future once i reach it on w3schools. Then i will return back to freecodecamp and redo couple of simmilar challenges.


#6

I reviewed the w3schools.com instructions, and actually the whole point of that exercise was just to teach you about the split method available for strings. If you just wanted to add a <br> after each letter of the original string, you could write:

<script>
var str = "Hello";
var text = "";
for (var i = 0; i < str.length; i++) {
    text += str[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>

You can reference a string’s index the same way you can an array, so the split was unnecessary, but apparently the lesson was less about changing the string and more about how to split a string into an array.


#7

Thank you very much for your help i really appreciate it. I know it was about showing us string methods only but i was very curious about loop being used and the way it worked there, i havent used for loops in a while.