Vahn
Vahn

Reputation: 542

Why is there "undefined" text in the beginning of my string?

I have a function that concatenates together the results from an AJAX request.

For some reason, my final string starts with "undefined".

Here is a simplified example that reproduces the problem:

    // In practice, fetched via AJAX from a server
    var vendors = [{ id_vendor: 'V0001' }, { id_vendor: 'V0002' }];

    var row_vendor;

    vendors.forEach(function (value) {
      row_vendor += value.id_vendor;
    });
	
    alert(row_vendor); // undefinedV0001V0002

Why does the value alerted display a leading "undefined"?

Upvotes: 1

Views: 4210

Answers (3)

user229044
user229044

Reputation: 239452

You're not initializing your variable, so its value is undefined. Concatenating a string coerces it to the string "undefined" before the concatenation.

Consider:

var x
alert(x + "test") // undefinedtest

Instead, initialize your variable to an empty string before performing concatenation:

var x = ""
alert(x + "test") // test

Note that functionally it is much cleaner to first extract the property you're interested in and then simply join them together:

$.map(vendor, function (v) { return v.vendor_id }).join('')

Upvotes: 6

asprin
asprin

Reputation: 9833

The issue is on this line

$.each(vendor, function(i, value) {
  row_vendor += value.id_vendor;
});

In order to use row_vendor for concatenation purpose, you first have to have a default value assigned to it. So what you would need to do is:

var row_vendor = ""; // set it to empty string by default
$.each(vendor, function(i, value) {
   row_vendor += value.id_vendor;
});

On a sidenote, you can also concatenate a string using an array. I prefer it this way since it's more pretty and readable.

var row_vendor = []; // empty array
$.each(vendor, function(i, value) {
   row_vendor.push(value.id_vendor);
});
console.log(row_vendor.join(",")); // this will separate each value with a comma

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150080

Your row_vendor variable is not assigned an initial value, so it starts out undefined and then using the += operator on it to concatenate a string results in undefined becoming the string "undefined" (plus the "v0001"). Simply set it to an empty string when you declare it:

var row_vendor = "";

Upvotes: 2

Related Questions