You should dynamically build strings without using strings.
How do you build strings when you need them conditionally built? For example, you need comma separated planets
from an array of astronomical bodies.
1
2
3
4
5
6
7
8
9
10
11
12
|
const astroBodies = [
{ name: "earth", type: "planet" },
{ name: "moon", type: "satellite" },
{ name: "mars", type: "planet" }
];
let planets = "";
astroBodies.forEach(ele => {
if (ele.type == "planet") planets += "," + ele.name;
});
console.log(planets); // ,earth,mars
|
You could do this, and this works. However it is not ‘clean’. For e.g. you have an extra “,”, strings are not friendly to manipulation of elements, and so forth.
The solution is not quite difficult - just use arrays in such instances. Use a join
when you need the final result as a string.
1
2
3
4
5
6
7
8
9
10
11
12
|
const astroBodies = [
{ name: "earth", type: "planet" },
{ name: "moon", type: "satellite" },
{ name: "mars", type: "planet" }
];
const planets = [];
astroBodies.forEach(ele => {
if (ele.type == "planet") planets.push(ele.name);
});
console.log(planets.join(",")); // earth,mars
|