How to avoid undefined in string concatenation?

I iterate over an object and I want to bind a service name. This is my code:

var servizi;

for(var i = 0; i < appointment.id_services.length; i++)
{
    servizi += appointment.id_services[i].name + " ";
}

Now the problem is that I got this result:

undefined hair cutting

My object has only hair and cut, why am I also getting undefined?

+4
source share
2 answers

You get undefined because you declared an uninitialized variable and then added to it (twice).

Initialize declared variable as empty string first

var servizi = "";
+5
source

intialize variable for empty string

var servizi = "";
+3
source

Source: https://habr.com/ru/post/1618103/


All Articles