How to avoid undefined in string concatenation? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to avoid undefined in string concatenation? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m iterating over an object and I want to concatenate the name of the service. 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’s that I got this result:

undefined hair cut

In my object there’s only hair and cut, why I get undefined also?

Answer

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

Initialize the declared variable as an empty string first

var servizi = "";
We are here to answer your question about How to avoid undefined in string concatenation? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji