Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid undefined in string concatenation?

Tags:

javascript

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?

like image 575
Dillinger Avatar asked Dec 01 '15 11:12

Dillinger


3 Answers

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 = "";
like image 89
Rokin Avatar answered Oct 12 '22 20:10

Rokin


intialize variable to empty string

var servizi = "";
like image 43
saikumarm Avatar answered Oct 12 '22 20:10

saikumarm


Uninitialized variables always begin with a value of undefined.

let servizi; // typeof(servizi) is undefined

So when you attempt to concatenate a string onto an undefined variable, the word "undefined" is converted to a string and added to the start. To avoid this, initialize the variable as an empty string.

let servizi = "";
like image 26
Jonathan Bernal Avatar answered Oct 12 '22 21:10

Jonathan Bernal