JS: Arrays
Theory: Generating strings with a loop
Using a loop to generate strings is common in real-world development. A function for generating HTML lists is a good example. It takes a collection of elements as an input and returns an HTML list of them:
This problem can, of course, be solved by brute force:
-
- Create a variable called
resultwith the value<ul>.
- Create a variable called
- Loop through the elements in the collection and add another
<li>element to the result each time. -
- Add
</ul>at the end and returnresultat the end of the function.
- Add
This method works, but for most programming languages it's really inefficient. The point is that concatenation and interpolation both generate a new string instead of using the old one, and this situation is repeated with each iteration, and the string gets bigger and bigger. Copying strings wastes a lot of memory and can affect performance. Of course, for most applications, this problem is irrelevant because of the small amount of data being processed, but the more efficient approach is no less difficult to implement and has several advantages. Therefore, it's worthwhile getting used to doing it the best way now.
The correct way, in the case of dynamic languages, is to form an array, which you can then turn into a string using the join() method:
The code size remains almost unchanged, but the way the result is generated is different. Instead of a string, first an array is collected, which is then converted to a string using the join() method. In addition to efficiency, this approach has a few additional advantages:
- This code is easier to debug. Data represented by an array is easier to isolate visually and programmatically
- An array is a structure, which means it can be modified further. There's not much you can do with a ready-made string
By adjusting the separator, lines can be combined in different ways. For example, with a comma and a space:
If each word has to be printed on a new line, we use the line feed character '\n' as a separator:
The last example is especially important. Beginners often make the mistake of adding a line break when the array is formed, rather than in join(). Look at the example with our buildHTMLList() function:
Recommended programs
Completed
0 / 22

