Homer_J Homer_J - 4 months ago 16
Javascript Question

Why does this alert contain undefined?

This is my code and it gets options from a jsTree checkbox tree list:

var level1, r = [];

for (i = 0, j = data.selected.length; i < j; i++) {
r[0] = data.instance.get_node(data.selected[i]).text.trim();
r[1] = data.instance.get_node(data.selected[i]).parents.length;

if(r[1] == 1) {
level1 += r[0] + ", ";
alert(level1);
}
}


The
alert
of the above contains
undefined
along with the correct choices from the checkboxes. Any idea why I am getting undefined in the output?

Answer Source

The problem is that level1 is undefined when you first try to use it here:

level1 += r[0]+", ";

That's the same as:

level1 = level1 + r[0]+", ";

The problem is level1 undefined the first iteration through and so the text contains undefined and concatenating it concatenates "undefined" as a string as it is coerced. Initialize it to an empty string:

var level1 = "";

That way it will not be undefined when you access it.