Learning Learning - 5 months ago 11
jQuery Question

String variable prefixed with undefined in for loop

I have a drop-down on which i use .Change() to trigger a function. Function basically get certain data using

getJSON
and based on those value in have to create string of array for mp3 file.

Below code is generating string but always prefix
undefined
to string.

In code you will notice
setTimeout
which is just to provide certain delay till data received. In below example i am using static value and it still prefix
undefined
. not sure why may be i have defined variable in wrong manner.

Complete example JSBin

$('.customSurah').change(function(){
//surahNo = $('#surah option:selected').val();

setTimeout(function(){
//countSpan = $('#surah-wrapper').children().length;
surahNo = 1;
countSpan = 7;
var i=0;
for (i = 0; i <= countSpan; i++) {
strCat += surahNo+"/"+i+".mp3,";
console.log(strCat);
}
}, 3000);

});


OUTPUT

undefined114/0.mp3,
undefined114/0.mp3,114/1.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,114/6.mp3,

Answer

You have a variable strCat that is not initialized, and then you append a value to it in this line:

strCat += surahNo+"/"+i+".mp3,";

Since strCat is not initialized in first round of loop, you get undefined prepended to your string.

To fix this, you need to initialize the variable to empty value first:

var strCat = '';   // <- initialize your variable to empty value
surahNo = 1;
countSpan = 7;