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?
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 = "";
intialize variable to empty string
var servizi = "";
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 = "";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With