Why does this piece of code return - null - when it should return - - by my understanding – it seems to be treating null like a string.
var testvar = null;
alert(" - "+testvar+" - ");
Thats it. The same goes for undefined. I need this to work as I have an array, and I loop to loop through the array, and add each item to a variable, which is a string.
I have this:
//'resp' variable is a JSON response, decoded with JSON.parse. This part works fine.
var addOnEnd=null;
for (item in resp) {
console.log(">"+item);
addOnEnd += item+"\n";
}
The console.log reads what I’d expect – a list of all the items in the response.
However, if I alert(addOnEnd) after the for loop, it returns ‘undefined’ (literally the string) and then the rest of the array as it should.
What am I doing wrong?
Change it to this:
alert(" - " + (testvar || "") + " - ");…and this…
addOnEnd += (item || "") + "\n";You will also need to initialize addOnEnd as an empty string instead of null.
This way, if the value is undefined (which when evaluated as a boolean returns false) it’ll use the ‘default’ value of an empty string.